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.
LeetCode Problem - 3147
class Solution {
public String clearDigits(String s) {
// Initialize a StringBuilder to construct the final string
StringBuilder sb = new StringBuilder();
// Iterate over each character in the input string
for (int i = 0; i < s.length(); i++) {
// Check if the current character is a digit
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
// If there are characters in the StringBuilder, delete the last character
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
} else {
// If the current character is not a digit, append it to the StringBuilder
sb.append(s.charAt(i));
}
}
// Return the final string constructed by the StringBuilder
return sb.toString();
}
}