LeetCode:Longest Valid Parentheses

來源:互聯網
上載者:User

標籤:leetcode   dp   

           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做,不過自己用棧寫的O(N)的解法沒有dp的快,所以說下dp的思路吧.

首先,看下狀態的定義:

  • dp[i]:表示選了第i個字元能組成的最長有效括弧個數.
通過上面狀態的定義,很容易得出下面的狀態轉移方程:


這裡解釋下第二個狀態方程的得來,當s[i]=‘)‘時,tmp表示的就是與s[i]對應的那個字元,如果其滿足條件
(tmp>=0 && s[tmp]==‘(‘)那麼就說明tmp到i這部分是有效括弧匹配,而tmp之前的也有可能存在有效括弧匹
配,所以需要將兩者相加,需要注意的是,邊界的地方.
解題代碼:
class Solution {public:    int longestValidParentheses(string s)     {        int n = s.size(), dp[n];        dp[0] = 0;        for (int i = 1; i < n; ++i)        {            int tmp = i - 1 - dp[i - 1];            if (s[i] == '(')                dp[i] = 0;            else if (tmp >= 0 && s[tmp] == '(')                dp[i] = dp[i - 1] + 2 + (tmp - 1 >= 0 ? dp[tmp - 1] : 0);            else                dp[i] = 0;        }        return *max_element(dp, dp + n);    }};


     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.