-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclearDigits.java
More file actions
27 lines (21 loc) · 757 Bytes
/
clearDigits.java
File metadata and controls
27 lines (21 loc) · 757 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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.
TC: O(N)
SC: O(1)
class Solution {
public String clearDigits(String s) {
StringBuilder res = new StringBuilder();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
res.deleteCharAt(res.length()-1);
} else{
res.append(c);
}
}
return res.toString();
}
}