leetcode 之 Longest Valid Parentheses

來源:互聯網
上載者:User

標籤: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:

"((()))", "(()())", "(())()", "()(())", "()()()"

該問題是著名的卡特蘭數,具體參考該部落格

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.