qingcheng奕  

http://oj.leetcode.com/problems/longest-valid-parentheses/

最大括号匹配长度,括号是可以嵌套的

 

#include <string>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
    int longestValidParentheses(string s) {
        const int s_len = s.size();

        stack<int> indexstack;
        vector<bool> flagvector;
        int templen = 0;
        int maxlen = 0;
        flagvector.resize(s_len);

        for(int index = 0;index<s_len;index++)
            flagvector[index] = false;

        for(int i = 0;i<s_len;i++)
        {
            if(s[i]==')')
            {
                if(indexstack.size()!=0)
                {
                    flagvector[indexstack.top()] = true;
                    flagvector[i] = true;
                    indexstack.pop();
                }
 
            }
            if(s[i]=='(')
            {
                indexstack.push(i);
            }
        }
        for(int index = 0;index<s_len;index++)
        {
            if(flagvector[index]==false)
            {
                maxlen = maxlen>templen?maxlen:templen;
                templen = 0;
            }
            else
                templen++;
        }
        maxlen = maxlen>templen?maxlen:templen;
        return maxlen;
    }
}; 
#include <iostream>
#include "cla.h"
using namespace std;
int main()
{
    Solution * mysolution = new Solution();
    string str = "";
    cout<<mysolution->longestValidParentheses(str)<<endl;
    return 0;
}

 

 

posted on 2013-10-26 10:51  qingcheng奕  阅读(132)  评论(0编辑  收藏  举报