Yet another Java O(N) solution, using stack (16ms)


  • 0
    J
    public class Solution {
        public int longestValidParentheses(String s) {
            if (s.length() < 1) return 0;
            char[] chars = s.toCharArray();
            int p = 0;
            int res = 0;
            int[] stack = new int[chars.length + 1];
            stack[0] = -1;
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == '(') stack[++p] = i;
                else if (p == 0) stack[0] = i;
                else res = Math.max(res, i - stack[--p]);
            }
            return res;
        }
    }
    

Log in to reply
 

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