码迷,mamicode.com
首页 > 其他好文 > 详细

32. Longest Valid Parentheses

时间:2018-10-12 16:07:49      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:com   问题   .com   rom   long   rip   i++   vector   tor   

https://leetcode.com/problems/longest-valid-parentheses/description/

来回做了好几遍,虽然AC 了但是这个解发肯定不是最优的。思路是把问题分两步解决:1. 把字符串转换成一个匹配括号的id 序列,比如第0 个和第3 个匹配了,则把0,3都记录在一个数组里。2. 排序生成的这个数组,然后遍历一次找最长的连续串,比如1235 里面,123 就是最长的连续串。排序是必要的,考虑这个例子:()(()),生成的序列是012325, 排序以后则是12345,反应了匹配的括号是确实是连续的。

class Solution {
public:
    int longestValidParentheses(string s) {
        //transform the problem into 2 sub problems
        //1. convert string into match pairs
        //2. calculate connectivity from pairs
        
        if (s.length() < 2) {
            return 0;
        } 
        
        //converting matching pair
        vector<int> stack;
        vector<int> pairs;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == () {
                stack.push_back(i);
            }
            else if (stack.size() > 0) {
                auto top = *(stack.end()-1);
                stack.pop_back();
                pairs.push_back(top);
                pairs.push_back(i);
            }
        }
        
        //check conseqtivity
        std::sort(pairs.begin(), pairs.end());
        if (pairs.size() == 0) {
            return 0;
        }
        int last = pairs[0];
        int cur;
        int acc = 0;
        int m = 0;
        for (int i = 1; i < pairs.size(); i++) {
            cur = pairs[i];
            if (cur - last == 1) {
                acc++;
            } else {
                m = std::max(acc+1, m);
                acc = 0;
            }
            last = cur;
        }
        
        if (acc > 0) {
            m = std::max(acc+1, m);
        }
        
        return m;
    }
};

 

32. Longest Valid Parentheses

标签:com   问题   .com   rom   long   rip   i++   vector   tor   

原文地址:https://www.cnblogs.com/agentgamer/p/9778254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!