Software engineer

LC- Valid Parentheses

LC- Valid Parentheses

Valid Parentheses

Question

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

Input: s = “()”

Output: true

Input: s = “(]”

Output: false

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<>();
        for(char c:s.toCharArray()){
            if(c=='('){
                stack.push(')');
            }else if(c=='['){
                stack.push(']');
            }else if(c=='{'){
                stack.push('}');
            }else{
                if(stack.empty()) return false;
                char temp=stack.pop();
                if(c!=temp){
                    return false;
                }
            }
        }
        if(!stack.empty()){
            return false;
        }return true;
    }
}
comments powered by Disqus