Share my solutions with stack


  • 0
    S
    public class Solution {
    public boolean isValid(String s) {
        if(s.length()<2){
            return false;
        }
        Stack<Character> stack = new Stack<Character>();
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='('||c=='['||c=='{'){
                stack.push(c);
            }else{
                if(stack.empty()){
                    return false;
                }
                char a = stack.peek();
                if(a=='('&&c!=')'){
                    return false;
                }
                if(a=='['&&c!=']'){
                    return false;
                }
                if(a=='{'&&c!='}'){
                    return false;
                }
                stack.pop();
            }
        }
        if(stack.empty()){
            return true;
        }else{
            return false;
        }
    }
    

    }


Log in to reply
 

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