본문 바로가기
Problem Solving/LeetCode

[LeetCode] 20. Valid Parentheses - Java

by graycode 2026. 5. 12.

 문제 링크

 

Valid Parentheses - LeetCode

Can you solve this real interview question? 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 sam

leetcode.com

 

 풀이 코드

public class Solution {

    public boolean isValid(String s) {
        char[] stk = new char[s.length() + 1];
        int top = 1;
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') stk[top++] = c;
            else if (Math.abs(c - stk[--top]) > 2) return false;
        }

        return top == 1;
    }

}

댓글