標籤:longest valid parent 動態規劃 leetcode 面試 棧
leetcode中和括弧匹配相關的問題共有三個,分別是:
Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and ‘]‘, determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
該提比較簡單,正常情況下直接用堆棧就可以了,但有一次面試要求必須要用遞迴寫,其實也很簡單,具體參考這裡
Longest Valid Parentheses
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.
該題目使用動態規劃來計算,dp[i]表示到第i個位置的最大長度,由於匹配的括弧必須是連續的,所以,如果有j < i 且j和i匹配,則dp[i] = (i-j+)+dp[j]。
從轉移方程來看,好像是二維DP,但是可以使用堆棧來轉化為一維的,簡單來說,就是遇到左括弧就進棧,遇到右括弧就出棧,而出棧的位置就是上
面的j,所以不需要進行二維掃描就可定位到j。
class Solution {public: int longestValidParentheses(string s) { int length = s.size(),i,maxLength = 0; vector<int> dp(length,0); stack<int> stk; // 左括弧的下標 for(i = 0; i < length;++i) { if(s[i] == '(')stk.push(i); else { if(!stk.empty()) { int start = stk.top(); stk.pop(); dp[i] = i - start + 1; if(start > 0)dp[i] += dp[start-1]; if(dp[i] > maxLength)maxLength = dp[i]; } } } return maxLength; }};
Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
該問題是著名的卡特蘭數,具體參考該部落格