402. 移掉K位數字
阿新 • • 發佈:2020-07-14
方法一:
class Solution { public String removeKdigits(String num, int k) { int n = num.length(); if(n <= k) return "0"; StringBuilder sb = new StringBuilder(num); for(int i = 0; i < k; i++) { int idx = 0; // 找到第一個大於後面的字元刪除它 for(int j = 1; j < sb.length() && sb.charAt(j) >= sb.charAt(j-1); j++) idx = j; sb.delete(idx,idx+1); // 去除前導0 while(sb.length() > 1 && sb.charAt(0) == '0') sb.deleteCharAt(0); } return sb.toString(); } }
方法二:單調棧
class Solution {public String removeKdigits(String num, int k) { int n = num.length(); if(n <= k) return "0"; Stack<Integer> stack = new Stack<>(); for(int i = 0; i < n; i++) { int m = num.charAt(i) - '0'; while(k > 0 && !stack.empty() && stack.peek() > m) { k--; // 記錄每一個之前大於當前元素的值,刪除它 stack.pop(); } stack.push(m); } while(k-- > 0) { stack.pop(); } StringBuilder sb = new StringBuilder(); while(!stack.empty()) { sb.append(stack.pop()); } while(sb.length() > 1 && sb.charAt(sb.length()-1) == '0') { sb.deleteCharAt(sb.length()-1); } return sb.reverse().toString(); } }