您的位置:首页 > 其它

[leetcode]longest Valid Parentheses(!!)

2013-01-08 06:00 369 查看
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int nSize = s.size();
int max = 0;
int begin = nSize;// where a part of legal parentheses begin
stack<int> stk;
for(int i = 0; i< nSize; ++i){
if(s[i] == '('){
stk.push(i);
}
else if(!stk.empty()){
int tmp = stk.top();
stk.pop();
begin = begin < tmp ? begin : tmp;
if(stk.empty())
max = max > i - begin + 1 ? max : i - begin +1;
else
max = max > i - stk.top()? max : i - stk.top();
}
else{
begin = i + 1;
}
}
return max;
}
};


充分利用了begin 和stk.top这个两个信息!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: