LeetCode 402: Remove K Digits
阿新 • • 發佈:2017-10-08
spa amp tco sta size empty not zeros div
Note:
1. Find a increasing digits number. It‘s kind of longest increasing subsequence but with fixed size.
2. Remember to remove the zeros from beginning.
class Solution { public String removeKdigits(String num, int k) { if (num.length() == 0) return "0"; int i = 1; Stack<Character> stack = newStack<>(); stack.push(num.charAt(0)); while (i < num.length()) { while (k > 0 && !stack.isEmpty() && num.charAt(i) < stack.peek()) { k--; stack.pop(); } stack.push(num.charAt(i++)); }while (k > 0 && !stack.isEmpty()) { stack.pop(); k--; } StringBuilder result = new StringBuilder(); while (!stack.isEmpty()) { result.insert(0, stack.pop()); } while (result.length() > 1 && result.charAt(0) == ‘0‘) result.deleteCharAt(0);return result.length() == 0 ? "0" : result.toString(); } }
LeetCode 402: Remove K Digits