LeetCode 솔루션 분류

[Easy - wk1 - Q4] 20. Valid Parentheses

컨텐츠 정보

본문

20. Valid Parentheses 


Given a string s containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

 

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

관련자료

댓글 4

yuun님의 댓글

  • 익명
  • 작성일
class Solution:
    def isValid(self, s: str) -> bool:
        valid = {')':'(', ']':'[', '}':'{'}
        tmp = []
        for i in s:
            if i not in valid:
                tmp.append(i)
            else:
                if tmp and tmp[-1] == valid[i]:
                    tmp.pop()
                else:
                    return False
                
        return len(tmp) == 0

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    
    private HashMap<Character, Character> map = new HashMap<Character, Character>();
    public boolean isValid(String s) {
        
        initMap();
        Stack<Character> stack = new Stack<Character>();
        
        for(int i=0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)){
                char top = stack.isEmpty()? 'c' : stack.pop();
                if(top != map.get(ch)){
                    return false;
                }
            }else{
                stack.push(ch);
            }
        }
        
        return stack.isEmpty();
        
    }
    
    private void initMap(){
        map.put(')','(');
        map.put('}','{');
        map.put(']','[');
    }
}

Chloe님의 댓글

  • 익명
  • 작성일
class Solution:
    def isValid(self, s: str) -> bool:

        while ('()' in s) or ('[]' in s) or ('{}' in s):
            s = s.replace('()', '').replace('[]', '').replace('{}', '')
        return s==''

Jack님의 댓글

  • 익명
  • 작성일
Python

Runtime: 56 ms, faster than 21.31% of Python3 online submissions for Valid Parentheses.
Memory Usage: 14 MB, less than 25.60% of Python3 online submissions for Valid Parentheses

class Solution:
    def isValid(self, s: str) -> bool:
        stack=[]
        table={
            ')':'(',
            '}':'{',
            ']':'['
        }
        
        for char in s:
            if char not in table:
                stack.append(char)
            elif not stack or table[char] != stack.pop():
                return False
        return len(stack) == 0
LeetCode 솔루션 357 / 14 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 580 명
  • 오늘 방문자 5,281 명
  • 어제 방문자 8,551 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,563 명
알림 0