402:移掉K位数字

This commit is contained in:
huangge1199 2021-04-25 09:42:28 +08:00
parent 9405fda740
commit 119d05496a

View File

@ -67,8 +67,9 @@ public class RemoveKDigits {
for (; i < num.length() - 1; i++) { for (; i < num.length() - 1; i++) {
while (i + 1 < num.length() && num.charAt(i) > num.charAt(i + 1) && remove < k) { while (i + 1 < num.length() && num.charAt(i) > num.charAt(i + 1) && remove < k) {
num = num.substring(i + 1); num = num.substring(i + 1);
i=0;
remove++; remove++;
while (!stack.isEmpty() && i + 1 < num.length() && stack.peek() > num.charAt(i + 1) && remove < k) { while (!stack.isEmpty() && i < num.length() && stack.peek() > num.charAt(i) && remove < k) {
stack.pop(); stack.pop();
remove++; remove++;
} }
@ -80,6 +81,7 @@ public class RemoveKDigits {
stack.push(num.charAt(i)); stack.push(num.charAt(i));
} }
} }
num = num.substring(i);
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
num = stack.pop() + num; num = stack.pop() + num;
} }