본문 바로가기

코딩테스트 준비/Leetcode

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 '()[]{}'.

 

이번 문제는 열린것과 닫친것의 순서를 잘 맞추는게 핵심인것 같음.

 

1. 열린것과 닫는것의 순서를 맞춰주기 위해 Last in First Out의 Stack 사용.

2-1. '(', '{' '[' 열린것을 만나면 stack에 열린것과 상응하는 닫는 부분 ')', '}', ']'을 넣어주고

2-2. ')', '}', ']' 부분을 만나면 stack에 넣어준 닫힌부분과 맞는지 비교.

3. 하나라도 틀리면 return false,  모든 것이 다 맞고 stack에거 맞게 다 잘 꺼내졌으면 return false. 

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
	    for (char c : s.toCharArray()) {
		    if (c == '(')
			    stack.push(')');
		    else if (c == '{')
			    stack.push('}');
		    else if (c == '[')
			    stack.push(']');
		    else if (stack.isEmpty() || stack.pop() != c)
			    return false;
	    }
	    return stack.isEmpty();
    }
}

'코딩테스트 준비 > Leetcode' 카테고리의 다른 글

1. Two Sum  (0) 2022.07.27
리츠코드 문제.  (0) 2022.07.27