[LeetCode/20] Valid Parentheses - JAVA

이지환·2024년 4월 15일

알고리즘(leetcode)

목록 보기
1/2
post-thumbnail

📌 Problem

Algorithm Classification : stack
Difficulty Level : easy
Source : LeetCode - 20. Valid Parentheses

🦧 Problem Solving Approach

first, I use stack algorithm.
if index of 'String s' is '(' or '{' or '[', push it.
and then if index of 'String s' is ')' or '}' or ']', check stack.

if last stack is each '(' or '{' or '[', pop it.
but else, return false

At last, check the size of the stack. If the stack's size is not 0, return false; otherwise, return true.

💻 Code

import java.util.Stack;

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i=0;i<s.length();i++) {
            if(s.charAt(i)=='(' || s.charAt(i)=='{' || s.charAt(i)=='[')
                stack.add(s.charAt(i));
            else if(stack.empty())
                return false;
            else if(s.charAt(i)==')' && stack.pop()=='(');
            else if(s.charAt(i)=='}' && stack.pop()=='{');
            else if(s.charAt(i)==']' && stack.pop()=='[');
            else return false;
        }
        if(stack.empty())
            return true;
        else
            return false;
    }
}

🥇 Result

🎓 Conclusion

A few exceptions should be considered well.

ex) [, [](, [(])

profile
takeitEasy

0개의 댓글