您的位置:首页 > 其它

LeetCode OJ——Longest Valid Parentheses

2013-10-26 10:49 459 查看
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;
}
};


View Code

#include <iostream>
#include "cla.h"
using namespace std;
int main()
{
Solution * mysolution = new Solution();
string str = "";
cout<<mysolution->longestValidParentheses(str)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: