SeangG
def _(): _()
SeangG
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Programming Language (0)
      • Python (0)
      • Web (0)
    • Algorithm (34)
    • Art (0)
      • 3D Modeling (0)
      • Pixel (0)
      • Picture (0)
    • Game (0)
    • Project (3)
      • Problems (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • dfs
  • string
  • Fast Refresh
  • LeedCode
  • react.js
  • Daily Question
  • 매핑 테이블
  • Python
  • 로마 숫자
  • graph
  • BFS
  • leetcode
  • Queue
  • Tree
  • 문자열
  • WSL
  • next.js
  • spring boot
  • Leecode
  • github oauth

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
SeangG

def _(): _()

Algorithm

[LeetCode] 678. Valid Parenthesis String (Daily Question)

2024. 4. 7. 22:43

문제



Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

The following rules define a valid string:
    - Any left parenthesis '(' must have a corresponding right parenthesis ')'.
    - Any right parenthesis ')' must have a corresponding left parenthesis '('.
    - Left parenthesis '(' must go before the corresponding right parenthesis ')'.'*' 
    - could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".

 

문자열 s가 주어졌을 때 괄호짝이 맞는 지 판단하는 문제이다.

여기서 '*'은 필요에 따라 여는괄호, 닫는괄호, 비어있음을 의미한다.

 

예를 들면 "*)"이 주어졌을 때 *이 (역할을 해 줄 수 있기 때문에 True를 반환한다.

Example 1:
Input: s = "()"
Output: true

Example 2:
Input: s = "(*)"
Output: true

Example 3:
Input: s = "(*))"
Output: true




 

풀이


아이디어

문자열을 앞에서부터 살펴보며 *을 세고, 열린괄호보다 닫힌괄호가 많아질 경우 *을 소모한다.

그리고 뒤에서부터 살펴보며 닫힌괄호와 열린괄호를 바꾸어 생각한다.

 

코드

class Solution:
    def checkValidString(self, s: str) -> bool:
        cnt = 0
        spare = 0
        
        # 앞에서부터 살펴봄
        for c in s:
            # (, ), * 개수 카운트
            if c == '(': cnt += 1
            elif c == ')': cnt -= 1
            else: spare += 1
                
            # (보다 )가 많아질 경우 *을 소모
            if cnt < 0:
                spare -= 1
                cnt += 1
                
            if spare < 0: return False
            
        if spare < cnt: return False
        
        cnt = 0
        spare = 0
        
        # 뒤에서부터 살펴봄
        for c in s[::-1]:
            if c == ')': cnt += 1
            elif c == '(': cnt -= 1
            else: spare += 1
                
            if cnt < 0:
                spare -= 1
                cnt += 1
            
            if spare < 0: return False
        
        return True

 


 

후기


난이도

아이디어만 떠올리면 구현은 어렵지 않은 문제인 듯 하다.

'Algorithm' 카테고리의 다른 글

[LeetCode] 2073. Time Needed to Buy Tickets (Daily Question)  (1) 2024.04.08
[LeetCode] 1700. Number of Students Unable to Eat Lunch (Daily Question)  (0) 2024.04.08
[LeetCode] 1249. Minimum Remove to Make Valid Parentheses (Daily Question)  (0) 2024.04.06
[LeetCode] 10. Regular Expression Matching  (0) 2024.04.05
[LeetCode] 1544. Make The String Great (Daily Question)  (0) 2024.04.05
    'Algorithm' 카테고리의 다른 글
    • [LeetCode] 2073. Time Needed to Buy Tickets (Daily Question)
    • [LeetCode] 1700. Number of Students Unable to Eat Lunch (Daily Question)
    • [LeetCode] 1249. Minimum Remove to Make Valid Parentheses (Daily Question)
    • [LeetCode] 10. Regular Expression Matching
    SeangG
    SeangG

    티스토리툴바