題目:
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.
鏈接:Longest Valid Parentheses
解法:用棧儲存左括號位置,檢查右括號匹配,若匹配則記錄兩者位置之差,即匹配括號長度。時間O(n)
class Solution {
public:
int longestValidParentheses(string s) {
int ans = 0;
stack<int> st;
st.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
st.push(i);
} else {
st.pop();
if (st.empty()) st.push(i);
else ans = ans > i - st.top() ? ans : i - st.top();
}
}
return ans;
}
};
Runtime: 9 ms