[LeetCode] 3174. Clear Digits (Python)

2025. 2. 10. 11:01·코딩 테스트
728x90

Problem

 

Solution

string, stack

문자열 s에서 digit이 있으면 digit 과 그 왼쪽에있는 문자를 제거하는 문제 (반복).

문자열을 순회하면서 해당 index를 기준으로 digit 여부와 왼쪽 문자를 체크하여 s 를 업데이트한 후 조건에 해당되지 않을 때까지 반복한다.

 

<다른 코드>

다른 코드에서는 alpha이면 list에 저장하고 그 다음 문자가 digit이면 pop하여 list에서 제거한 뒤 최종적으로 string으로 concat 해서 반환한다.

class Solution:
    def clearDigits(self, s: str) -> str:
        stack = []
        
        for char in s:
            if char.isdigit():
                if stack:  # 숫자가 나오면 이전 문자 삭제
                    stack.pop()
            else:
                stack.append(char)
        
        return ''.join(stack)

# 테스트 코드
sol = Solution()
print(sol.clearDigits("ab1c3d"))  # "cd"
  • 시간 복잡도 : O(N) -> 한 번만 순회
  • 공간 복잡도 : O(N) -> 리스트 사용

Code

class Solution:
    def clearDigits(self, s: str) -> str:
        indicies = []
        isDigit = False
        idx = 0

        while(idx < len(s)):
            if s[idx].isdigit():
                s = s[:(idx-1)] + s[idx+1:]
                # print(idx, s)
                idx = 0  
            idx += 1
                
        return s

 

Complexity

Time Complexity

모든 문자에대해서 digit을 만날때마다 다시 순회한다.

최악의 경우 n의 길이만큼 n번 반복하므로 O(N^2)

 

Space Complexity

새로운 문자열을 생성하므로 O(N)

728x90
저작자표시 비영리 변경금지 (새창열림)

'코딩 테스트' 카테고리의 다른 글

[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits (Python)  (0) 2025.02.12
[LeetCode] 1910. Remove All Occurrences of a Substring (Python)  (0) 2025.02.11
[LeetCode] 2364. Count Number of Bad Pairs (Python)  (0) 2025.02.09
[LeetCode] 2349. Design a Number Container System (Python)  (0) 2025.02.08
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)  (0) 2025.02.08
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits (Python)
  • [LeetCode] 1910. Remove All Occurrences of a Substring (Python)
  • [LeetCode] 2364. Count Number of Bad Pairs (Python)
  • [LeetCode] 2349. Design a Number Container System (Python)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    kafka
    스프링부트
    LeetCode
    코딩
    자료구조
    리트코드
    코딜리티
    CodingTest
    스프링
    springboot
    코테
    알고리즘
    java
    쿠버네티스
    Python
    db
    자바
    pythoncodingtest
    코딩테스트
    네트워크
    프로그래머스
    코테공부
    카카오코테
    Spring
    codility
    MySQL
    금융용어
    Kotlin
    C++
    이분탐색
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] 3174. Clear Digits (Python)
상단으로

티스토리툴바