个人技术分享

最朴实解法:

class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<>();
        int ans = 0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i) == '(')
                stack .push(i);
            else{
                if(stack.isEmpty()){
                    stack.push(i);
                }else{
                    if(s.charAt(stack.peek()) == '('){
                        stack .pop();
                        ans = stack.isEmpty() ? i+1 : Math.max(ans,i-stack .peek());
                    }else{
                        stack.push(i);
                    }
                }
            }
        }
        return ans;
    }
}

优化后:

class Solution {
    public int longestValidParentheses(String s) {
    int maxans = 0;
    Stack<Integer> stack = new Stack<>();
    stack.push(-1);
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            stack.push(i);
        } else {
            stack.pop();
            if (stack.empty()) {
                stack.push(i);
            } else {
                maxans = Math.max(maxans, i - stack.peek());
            }
        }
    }
    return maxans;
}
}

题解:
如果是’(‘,就直接push到栈中,如果是’)',移除栈顶元素,判断栈是否为空,如果为空push进去,如果不为空。。。

数据结构:
Stack stack = new Stack<>();

用到方法:
stack.push()
stack.pop()
stack.peek() 返回栈顶元素,但是不移除栈顶元素