3447. Clear Digits
2026/1/12大约 1 分钟约 397 字
3447. Clear Digits
难度: Easy
题目描述
You are given a string s.
Your task is to remove all digits by doing this operation repeatedly:
- Delete the first digit and the closest non-digit character to its left.
Return the resulting string after removing all digits.
Note that the operation cannot be performed on a digit that does not have any non-digit character to its left.
Example 1:
Input: s = "abc"
Output: "abc"
Explanation:
There is no digit in the string.
Example 2:
Input: s = "cb34"
Output: ""
Explanation:
First, we apply the operation on s[2], and s becomes "c4".
Then we apply the operation on s[1], and s becomes "".
Constraints:
1 <= s.length <= 100sconsists only of lowercase English letters and digits.- The input is generated such that it is possible to delete all digits.
解题思路
代码实现
解决方案
java
class Solution {
public String clearDigits(String s) {
LinkedList<Character> stack = new LinkedList<>();
char[] charArray = s.toCharArray();
LinkedList<Character> temp = new LinkedList<>();
for (int i = s.length() - 1; i > -1; i--) {
if (charArray[i] >= '0' && charArray[i] <= '9') {
stack.push(charArray[i]);
} else {
if (stack.isEmpty()) {
stack.push(charArray[i]);
continue;
} else {
boolean flag = false;
while (!stack.isEmpty()) {
char pc = stack.peek();
if (pc >= '0' && pc <= '9') {
stack.pop();
flag = true;
break;
}
temp.push(stack.pop());
}
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
if (!flag) {
stack.push(charArray[i]);
}
}
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
}