题解 | #最长的括号子串#

最长公共前缀

http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    int longestValidParentheses(string s) {
        // write code here
        int n = s.length();
        stack<int> stk;
        stk.push(-1); //最后一次未匹配的右括号
        int ans = 0;
        for(int i = 0; i < n; i ++){
            if(s[i] == '(') stk.push(i);
            else{
                stk.pop();
                if(stk.empty()) stk.push(i); //未匹配的右括号
                else{
                    ans = max(ans, i - stk.top());
                }
            }
        }
        return ans;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务