链接:www.nowcoder.com/practice/45…
思路:首先利用栈进行匹配左括号和右括号,匹配成功的丢掉,还剩下匹配不成功的,最后大概是)))))(((((这样的,把他们的的位置标记为false,合格的子串不会包括这些标记为false的位置,肯定是连续的标记为true的位置,只要再次遍历一遍找到最长的标记为true的位置就可以了
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int longestValidParentheses(string s) {
// write code here
const int maxn = 6e5;
bool vis[maxn];
stack<int> a;
for(int i=0;i<s.size();i++) {
if(s[i]=='(') {
a.push(i);
} else {
if(!a.empty()) {
vis[i] = true;
vis[a.top()] = true;
a.pop();
} else {
vis[i] = false;
}
}
}
while(!a.empty()) {
vis[a.top()] = false;
a.pop();
}
int cnt=0,mx = 0;
for(int i=0;i<s.size();i++) {
if(vis[i]) ++cnt;
else cnt=0;
mx = max(mx,cnt);
}
return mx;
}
};