1.题目分析
1.这种最长子串一般用dp实现,是以某个位置结尾,以某个位置开始;也可能会从后往前推。
2. 括号匹配,经常会使用栈;运算符中有括号也会使用栈。
2.示例代码
- dp实现
class Solution {
public:
int longestValidParentheses(string s) {
//以某个位置结尾的长度
int s_len = s.size();
vector<int> dp(s_len, 0);
int ret = 0;
for(int i = 1; i < s_len; ++i){
char c = s[i];
if(c == '('){
continue;
}else{
//等于右括号
int match_pos = i - dp[i-1] - 1;
if(match_pos < 0 || s[match_pos] == ')'){
continue;
}else{
dp[i] = 2 + dp[i-1] + (match_pos == 0 ? 0 : dp[match_pos - 1]);
ret = max(ret, dp[i]);
}
}
}
return ret;
}
};
- 栈实现
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int ret = 0;
for(int i = 0; i < s.size(); ++i){
int top = st.top();
//也是计算以每一个位置结尾的长度
if(top != -1 && s[top] == '(' && s[i] == ')'){
st.pop();
ret = max(ret, i - st.top());
}else{
st.push(i);
}
}
return ret;
}
};