Notice
250x250
Recent Posts
Recent Comments
Link
넘치게 채우기
[LeetCode] 3174. Clear Digits 본문
728x90
반응형
https://leetcode.com/problems/clear-digits/description/
leetcode - 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.
문자열 s를 받습니다.
당신의 임무는 다음을 반복적으로 수행하는 것 입니다:
- 첫 번째 숫자를 지우고 왼쪽의 숫자가 아닌 문자를 제거하시오
이 결과를 반환하시오.
풀이
스택을 이용해서 마지막으로 읽은 숫자가 아닌 문자를 쌓는다.
숫자를 읽으면 스택의 톱을 pop한다.
스택을 모두 꺼내서 문자열에 담고, 이러면 뒤집어져 있으니 문자열을 뒤집어서 반환한다.
코드
C++
#pragma GCC optimize("O3", "unroll-loops");
static const int __ = [](){
ios_base::sync_with_stdio(0);
cin.tie(0);
return 0;
}();
class Solution {
public:
string clearDigits(string s) {
stack<char> stk;
for(char ch : s) {
if(ch >= '0' && ch <= '9') {
if(!stk.empty()) {
stk.pop();
} else {
stk.push(ch);
}
} else {
stk.push(ch);
}
}
string ans;
while(!stk.empty()) {
ans += stk.top();
stk.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
Go
func clearDigits(s string) string {
stk := make([]byte, 0)
for _, v := range s {
if v >= '0' && v <= '9' {
if len(stk) > 0 {
stk = stk[:len(stk)-1]
} else {
stk = append(stk, byte(v));
}
} else {
stk = append(stk, byte(v));
}
}
return string(stk)
}
728x90
반응형
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 1910. Remove All Occurrences of a Substring (0) | 2025.02.11 |
---|---|
[LeetCode] 2364. Count Number of Bad Pairs (0) | 2025.02.09 |
[LeetCode] 2349. Design a Number Container System (0) | 2025.02.08 |
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (0) | 2025.02.07 |
[LeetCode] 1726. Tuple with Same Product (0) | 2025.02.06 |