Programming/LeetCode

[LeetCode] #20. Valid Parentheses

dev.pudding 2024. 2. 8. 14:32
728x90

Description 

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

An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.


Solution 

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();
        
        }
    
    }
}


 Shhhh.. didn't check that the open brackets are closed in the correct order.

 

 

https://leetcode.com/problems/valid-parentheses/?envType=study-plan-v2&envId=top-interview-150

 

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