Leetcode Problem:
Summary
- Remove all digits from a given string by deleting the first digit and the closest non-digit character to its left.
Approach
- Use a stack to store the non-digit characters and then join them into a string to get the final result.
Complexity
- O(n) where n is the length of the string
Explain
- The solution iterates through the string and pushes non-digit characters into the stack
- When a digit is encountered, it pops the top element from the stack
- Finally, it joins the characters in the stack into a string and returns it.
Solution Code:
class Solution {
public:
vector st;
string clearDigits(string s) {
for(int i = 0 ; i < s.size(); i++){
if(s[i] >= 'a' && s[i] <= 'z'){
st.push_back(s[i]);
}else{
if(st.size() != 0){
st.pop_back();
}
}
}
string res = "";
for(int i = 0 ; i < st.size(); i++){
res += st[i];
}
return res;
}
};
class Solution {
public:
vector st;
string clearDigits(string s) {
for(int i = 0 ; i < s.size(); i++){
if(s[i] >= 'a' && s[i] <= 'z'){
st.push_back(s[i]);
}else{
if(st.size() != 0){
st.pop_back();
}
}
}
string res = "";
for(int i = 0 ; i < st.size(); i++){
res += st[i];
}
return res;
}
};
'알고리즘' 카테고리의 다른 글
Most Stones Removed with Same Row or Column (0) | 2025.02.11 |
---|---|
Count Sub Islands (0) | 2025.02.11 |
N-ary Tree Postorder Traversal (0) | 2025.02.10 |
Binary Tree Postorder Traversal (0) | 2025.02.10 |
Find the Closest Palindrome (0) | 2025.02.10 |