leetcode 32. Longest Valid Parentheses

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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值