Why my java solution is "EmptyStackException" ?


  • 0
    V

    public class Solution {

    public int longestValidParentheses(String s) {
    
        if(s == null || s.length() == 0 || s.length() == 1){
            return 0;
        }
        
        Stack<Character> stack = new Stack<Character>();
        stack.push(s.charAt(0));
        int count = 0;
        
        for(int i = 1; i < s.length(); i++){
            if(s.charAt(i) == ')' && stack.peek() == '('){
                stack.pop();
                count = count + 2;
            }else{
                stack.push(s.charAt(i));
            }
        }
        
        return count;
    }
    

    }

    I have put first character of string s into the stack, but why it says: EmptyStackException ? the last execute input is " ( ) ) "


Log in to reply
 

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