래원

[LeetCode] 3174. Clear Digits (Python) 본문

알고리즘/LeetCode

[LeetCode] 3174. Clear Digits (Python)

Laewon Jeong 2025. 2. 10. 14:43

 

 

난이도: 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.

 

문제 예제


Example 1:

Input: s = "abc"
Output: "abc"
Explanation:
There is no digit in the string.

Example 2:

Input: s = "cb34"
Output: ""
Explanation:
First, we apply the operation on s[2], and s becomes "c4".

Then we apply the operation on s[1], and s becomes "".

 

제한 사항


  • 1 <= s.length <= 100
  • s consists only of lowercase English letters and digits.
  • The input is generated such that it is possible to delete all digits.

 

✏️ Solution(솔루션)


class Solution:
    def clearDigits(self, s: str) -> str:
        stack = []
        n = len(s)

        for i in range(n):
            if not s[i].isdigit():
                stack.append(s[i])
            else:
                if stack:
                    stack.pop()
        
        return ''.join(stack)

 

이 문제는 s에 숫자가 나오면 왼쪽에 가장 근처 알파벳이랑 같이 지웠을 때 남는 요소들을 반환하면 되는 문제였다.

 

stack을 이용해 간단히 해결할 수 있다.

 

s의 요소가 알파벳이라면 stack에 넣어준다.

 

만약 s의 요소가 숫자라고 한다면 stack의 마지막 요소를 pop해준다.

결국 stack 마지막 요소가 제일 가까운 왼쪽 알파벳이기 때문이다.

 

모든 요소를 탐색하고 stack에 남아있는 알파벳들을 반환하고 정답을 맞출 수 있었다.

 

아래 그림은 간단한 예시를 보여준다.


문제: 3174. Clear Digits

 

깃허브: github

 

algorithmPractice/LeetCode/3447-clear-digits at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com