您的位置:首页 > 其它

LeetCode 32 Longest Valid Parentheses

2015-11-12 05:46 519 查看
Given a string containing just the characters
'('
and
')'
, find the length of the longest valid (well-formed) parentheses substring.

For
"(()"
, the longest valid parentheses substring is
"()"
, which has length = 2.

Another example is
")()())"
, where the longest valid parentheses substring is
"()()"
, which has length = 4.

找到正确的最长括号串长度。

先来看我的愚蠢的N^3解法:

bool isValid(string s) { //判断一个字串是不是配对的括号序列
vector<char> stack;
int len = s.length();
for(int i = 0 ;i < len; i++){
if(stack.empty()){
stack.push_back(s[i]);
}
else if((stack.back()=='(' && s[i] == ')')){
stack.pop_back();
}
else{
stack.push_back(s[i]);
}
}
if(stack.empty()){
return true;
}
else
return false;
}

int longestValidParentheses(string s) {
if(s.length()<=1){
return 0;
}
vector<int > leftParentheseIndex;
for(int i = 0 ;i< s.length();i++){
if(s[i]=='('){
leftParentheseIndex.push_back(i);//找到所有"("的索引
}
}
int longestLength=-1;
for(int i = 0 ; i< leftParentheseIndex.size() ;i++){//对于每一个从"("开始的穿,找它所有的字串,看是不是有效地括号序列,记录最大长度
for(int j=leftParentheseIndex[i]+1; j<s.length(); j+=2 ){
if(isValid(s.substr(leftParentheseIndex[i],j-leftParentheseIndex[i]+1))){
if(j-leftParentheseIndex[i]+1>longestLength){
longestLength = j-leftParentheseIndex[i]+1;
}
}
}
if(longestLength>=s.length()-leftParentheseIndex[i]){
break;
}
}
return longestLength;
}


这个方法就不说了,要多蠢有多蠢,绝对的超时,因为重复计算了茫茫多的字串。

看看别人的方法:

int longestValidParentheses(string s)
{
stack<int>S;   //维护一个存放括号索引的栈,栈底存放上一次不匹配发生的位置
S.push(-1);
int ans=0;
for(string::size_type i=0;i<s.size();i++)
{
//printf("%d\n",S.size());
char ch=s[i];
if(ch == '(')  //存入遇到的所有"("的索引
{
S.push(i);
}
else
{
if(S.size()>1)  //如果是")"而且栈内有"("的索引,说明有可以消除的括号对
{
S.pop();  //消除那对括号即弹出"("的索引
int tmp=S.top();  //更新最大长度,为当前")"的索引和弹出"("后栈顶
ans=max(ans,(int)i-tmp); //元素的差 和 当且结果之间的最大值
}
else    //若栈内没有"("的索引,说明无法匹配,更新栈底的数据位当前索引
{
S.pop();
S.push(i);
}
}
}
return ans;
}


我怎么只能想到这么蠢得方法 T^T。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: