Monday, November 30, 2015

[leetcode]Longest Valid Parentheses

用charAt()一直超时 改成char array竟然过了...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public int longestValidParentheses(String s) {
        int longest = 0;
        Stack<Integer> stack = new Stack<Integer>();
        char array[] = s.toCharArray();
        for (int i = 0; i < array.length; i++){
            if (array[i] == ')' &&
                !stack.isEmpty() && array[stack.peek()] != ')'){
                stack.pop();
                if (stack.isEmpty()){
                    longest = Math.max(longest, i+1);
                }else{
                    longest = Math.max(longest, i-stack.peek());
                }
            }else{
                stack.push(i);
            }
        }
        return longest;
    }
}

No comments:

Post a Comment