Short java AC solution with stack


  • 0
    J
       public int longestValidParentheses(String s) {
            Stack<Integer> st = new Stack<>();
            st.push(-1);
            int len = 0;
            for(int i=0;i<s.length();i++){
                if(s.charAt(i)==')'&&st.peek()!=-1&&s.charAt(st.peek())=='('){
                    st.pop();
                    len = Math.max(len,i-st.peek());
                }
                else   st.push(i);
            }
            return len;
        }

Log in to reply
 

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