share my concise java code


  • 0
    B

    hope it helps : )

    public class Solution {
        public int longestValidParentheses(String s){
            if (s.length() <= 1){
                return 0;
            }
            char[] input = s.toCharArray();
            Deque<Integer> st = new LinkedList<>();
            int[] M = new int[input.length];
            M[0] = 0;
            st.push(0);
            int ans = 0;
            for (int i = 1 ; i < input.length ; i++){
                if (!st.isEmpty() && isValid(input, st.peek(), i)){
                    int pairIndex = st.pop();
                    M[i] = i - pairIndex + 1 + (pairIndex - 1 >= 0 ? M[pairIndex - 1] : 0);
                }else {
                    st.push(i);
                    M[i] = 0;
                }
                ans = Math.max(ans, M[i]);
            }
            return ans;
        }
        private boolean isValid(char[] input, int i, int j){
            return input[i] == '(' && input[j] == ')';
        }
    }
    

Log in to reply
 

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