leetcode 32. Longest Valid Parentheses
奇了怪了,为什么java版本的算法TLE,c++版本的代码acc,难到是两种语言本身的区别:String 以及 stack操作
java版本的:
package my;
import java.util.Stack;
public class Solution {
public static void main(String[] args){
Solution s = new Solution();
int k =s.longestValidParentheses("((((((((())))");
}
public int longestValidParentheses(String s) {
int slen = s.length();
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
for(int i=0;i<slen;i++){
char c = s.charAt(i);
if(c=='(') stack.push(i);
if(c==')') {
if(stack.size()==1) stack.push(i);
else{
int top = stack.peek();
char t = s.charAt(top);
if(t=='(') stack.pop();
else{
stack.push(i);
}
}
}
}
stack.push(slen);
if(stack.size()==slen+1) return 0;
int max = 0;
int cur = stack.pop();
int next;
while(stack.size()!=0){
next = stack.pop();
int dis = cur-next-1;
if(dis>max){
max = dis;
}
cur = next;
}
return max;
}
}
c++版本的:
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(), longest = 0;
stack<int> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(') st.push(i);
else {
if (!st.empty()) {
if (s[st.top()] == '(') st.pop();
else st.push(i);
}
else st.push(i);
}
}
if (st.empty()) longest = n;
else {
int a = n, b = 0;
while (!st.empty()) {
b = st.top(); st.pop();
longest = max(longest, a-b-1);
a = b;
}
longest = max(longest, a);
}
return longest;
}
};