My simple Java solution


  • 7
    P
    public int longestValidParentheses(String s) {
        Stack<Integer> st = new Stack<Integer>();
        int maxLen = 0;
        int curLen = 0;
        for(int i = 0; i < s.length();i++) {
            if(s.charAt(i) == '(') {
                st.push(curLen);
                curLen = 0;
            } else if (s.charAt(i) == ')') {
                if(st.isEmpty()) {
                    curLen = 0;
                } else {
                    curLen = curLen + st.pop() + 2;
                    if(curLen > maxLen) maxLen = curLen;
                }
            }
        }
        return maxLen;
    }

Log in to reply
 

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