【三角兽】2017散招实习面试题
题目地址:
最长括号匹配
在有左右括号的字符串中找出最大长度的子串,使得子串的括号能够匹配。
https://leetcode-cn.com/problems/longest-valid-parentheses/
解题思路:
利用一个辅助栈进行匹配。
如果是"(",则入栈,表示待匹配。
如果是")"。先出栈,出栈"("则表示当前匹配成功,出栈")"则表示把上次的")"索引更新。
栈为空,则需要更新索引,更新不匹配的位置。
最后用i-sta.top()则表示当前索引减去上次不匹配的位置。遍历一次取最大值即可。
AC代码:
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> sta;
sta.push(-1);
int res = 0, len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] == '(') { // 左括号进栈
sta.push(i);
} else {
sta.pop();
if (sta.empty()) {
sta.push(i);
}
res = max(res, i - sta.top());
}
}
return res;
}
};