알고리즘
Clear Digits
짬뽕얼큰하게
2025. 2. 10. 23:41
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;
}
};