Super Easy Understand Solution Java +1s


  • 0
    C

    have a look at the input, ()[]{} or ([]{}) ,in every valid input, there will be at least one valid pair, either be {}, [] ,or ()

    So every time we loop through the array,get the current character, we can check current char and the peek element in stack, for example

    if the current element is ']', check the peek element in the stack, if it is ']', pop this element, else return false,

    At last, the stack is empty, means it satisfy the requirement.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.