Java valid Parentheses solution using stack


  • 1
    V

    public class Solution {

    public boolean isValid(String s) {
    
        if(s == null || s.length() == 0 || s.length() == 1 || s.length() %2 != 0){
            return false;
        }
        
        Stack<String> stack = new Stack<String>();
        
       
        stack.push(s.substring(0, 1));
        
        for(int i = 1; i < s.length(); i++){
            if(s.substring(i, i+1).equals(")") && stack.peek().equals("(")){
                stack.pop();
            }else if(s.substring(i, i+1).equals("}") && stack.peek().equals("{")){
                stack.pop();
            }else if(s.substring(i, i+1).equals("]") && stack.peek().equals("[")){
                stack.pop();
            }else{
                stack.push(s.substring(i,i+1));
            }
        }
        
        if(stack.isEmpty()){
            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.