题目:Longest Valid Parentheses
原题链接:https://leetcode.com/problems/longest-valid-parentheses/?tab=Description
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.
给出一个字符串只含有小括号符号“(”以及“)”,找出字符串中合法的(即符合括号匹配规则)子串中的最长值。
例:
对与”(()”,最长的合法子串是 “()”,所以长度是2。
对于”)()())”,最长的合法子串是”()()”,所以长度是4。
思路
使用暴力查找的话会超时,效率很低。
我们可以先把字符串中已经配对好的那些子串给去掉,剩下的就只需要判断没有配对的括号之间的子串的长度就可以了。
代码
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length();
if(len < 2) return 0;
// st用来存放没有配对成功的字符的下标
stack<int> st;
// 扫描字符串,将没有办法配对成功的字符下标压入栈
for(int i = 0; i < len; ++i) {
if(s[i] == '(') st.push(i);
else{
if(!st.empty()){
if(s[st.top()] == '('){
st.pop();
}else{
st.push(i);
}
}else{
st.push(i);
}
}
}
int res = 0;
if(st.empty()){
res = len; // 栈空则整个字符串都是配对好的
}else{
// 每次选取栈顶元素,当前栈顶元素和前一个栈顶元素之间的区间则是配对符合要求的子串
int a = len, b = 0; // a用来表示区间的左,b用来表示区间的右,注意初始的时候假设右
// 是len
while(!st.empty()){
b = a;
a = st.top();
st.pop();
res = max(res, b - a - 1);
}
// 考虑栈底元素之前的子串
res = max(res, a);
}
return res;
}
};