15 lines java code beat 97%


  • 0
    L

    use int[] as stack

    public class Solution {
        public int longestValidParentheses(String s) {
            char[] str = s.toCharArray();
            int[] stack = new int[str.length+1];
            stack[0] = -1;
            int cnt = 0;
            int ans = 0;
            for(int i=0;i<str.length;i++){
                if(cnt>0 && str[stack[cnt]]=='(' && str[i]==')')
                    ans = Math.max(ans,i-stack[--cnt]);
                else
                    stack[++cnt]=i;}
            return ans;
        }
    }
    

Log in to reply
 

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