알고리즘

[leetcode] Valid Parentheses

nayeonee__ 2023. 10. 3. 14:14

[문제] https://leetcode.com/problems/valid-parentheses/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

 

import java.util.Stack;

public class Valid_Parentheses {
	  public static boolean isValid(String s) {
           // 문자열 s의 길이가 홀수일 경우 : 짝이 안맞음 - false 반환
            if (s.length() % 2 == 1) {
                return false;
            }
            
            Stack<Character> stack = new Stack<>();

            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
		// 여는 괄호일 때 stack 에 push
                if (ch == '(' || ch == '{' || ch == '[') {
                    stack.push(ch);
                }
                // 닫는 괄호 일 경우 스택이 비어있거나 맨위에 괄호가 해당 괄호가 아니라면 false 반환
                switch (ch) {
                    case ')':
                        if (stack.empty() || stack.peek() != '(') {
                            return false;
                        }
                        // 해당 괄호랑 짝이라면 스택에 있던 괄호 pop()
                        else {stack.pop();}
                        break;
                    case '}':
                        if (stack.empty() || stack.peek() != '{') {
                            return false;
                        }
                        else {stack.pop();}
                        break;
                    case ']':
                        if (stack.empty() || stack.peek() != '[') {
                            return false;
                        }
                        else {stack.pop();}
                        break;
                }
            }
            // stack 이 비어있다면 true 반환
            return stack.empty();
        }
    }

'알고리즘' 카테고리의 다른 글

[leetcode] Tow Sum  (0) 2023.10.13
[leetcode] Best Time to Buy and Sell Stock  (0) 2023.09.30
[leetcode] ContainsDuplicate  (0) 2023.09.29
[백준] 2309 _ 일곱난쟁이  (0) 2023.09.19
[백준] 13300 _ 방배정  (0) 2023.09.19