题目描述
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:
Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
思路
使用堆栈的思想,遍历这个字符串:
- 遇到‘(’,就把它的索引压入栈中
- 遇到‘)’,就把栈顶弹出:
- 弹出后如果栈不为空,就用当前索引减去栈顶储存的索引,得到的值便是该字符串其中一个有效括号序列的长度, 跟当前最大值比较,进行更新。
- 弹出后如果栈为空,就把当前索引压入栈中
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> mystack;
mystack.push(-1);
int res = 0;
for(int i = 0; i < s.size(); i++) {
if(s[i] == '(') {
mystack.push(i);
} else {
mystack.pop();
if(!mystack.empty()) {
res = max(res, i - mystack.top());
} else {
mystack.push(i);
}
}
}
return res;
}
};