Advertisement
1988coder

402. Remove K Digits

Dec 10th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. /*
  2. Time Complexity: O(N)
  3. Space Complexity: O(N)
  4.  
  5. N = Length of the num string.
  6. */
  7. class Solution {
  8.     public String removeKdigits(String num, int k) throws IllegalArgumentException {
  9.         if (num == null) {
  10.             throw new IllegalArgumentException("Input num string is null");
  11.         }
  12.         if (num.length() == 0 || num.length() <= k) {
  13.             return "0";
  14.         }
  15.         if (k == 0) {
  16.             return num;
  17.         }
  18.        
  19.         StringBuilder sb = new StringBuilder();
  20.         for (char c : num.toCharArray()) {
  21.             while (k > 0 && sb.length() != 0 && sb.charAt(sb.length()-1) > c) {
  22.                 sb.setLength(sb.length()-1);
  23.                 k--;
  24.             }
  25.             if (sb.length() == 1 && sb.charAt(0) == '0') {
  26.                 sb.setCharAt(0, c);
  27.             } else {
  28.                 sb.append(c);
  29.             }
  30.         }
  31.        
  32.         if (k > 0) {
  33.             sb.setLength(sb.length() - k);
  34.         }
  35.        
  36.         return sb.toString();
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement