1. 程式人生 > >程式設計之美---最長有效括號字串

程式設計之美---最長有效括號字串

題目

         給定字串,僅包含左括號‘(’和右括號‘)’,它可能不是括號匹配的,設計演算法,找出最長匹配的括號子串,返回該子串的長度。

         如:

                  (():2

                  ()():4

                  ()(()):6

                  (()()):6


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.

比如 (((())))(((()) 連續有效的括號對數 就是前四對 第九個 第十個 不能配對 所以後面的 兩對 不能算是 連續有效的
這是小弟寫的 水平有限 只能寫出這樣的了
當 字串為 "(((())))(((())" 檢測出是 6個 這是不對的 應該是四個


當字串為"(((()))))((())" 時候 檢測出是四個 這個是正確的

ps:“)((())(()” 有效括號數 是正數第3到6個單括號 計算連續有效的括號數 是從第一個有效括號開始 直到 碰到第一個組不成一對括號的一個 單括號;所以這個是從正數第三個單括號開始計算 到第6個單括號 因為第7無法組成有效的成對括號 所以 從第7(包含7) 後的都不算。

例子

         對於“(()”

                  i=0:(;

                  i=1:(;

                  i=2:);

                  因為,i=0是左括號(,入棧:

                            棧:(

                  因為i=1是左括號(,入棧:

                            棧:( (

                  因為i=2是右括號),和棧頂元素(下面紅色的那個)進行匹配:

                           棧:( (

                  所以棧頂元素出棧:

                           棧:(

                  因為i已經遍歷到最後,且棧不為空,所以令最後一個i=2減去棧頂元素i=0,即:2 - 0 = 2

         對於“())”

                  因為,i=0是左括號(,入棧:

                            棧:(

                  因為i=1是右括號),和棧頂元素(下面紅色的那個)進行匹配:

                           棧:(

                  所以棧頂元素出棧:

                           棧:

                  此時棧為空,因此ml = max( (i= 1) - (start = 0), ml ) = 1

                  因為,i=2是左括號),且已經遍歷到最後,且棧為空,所以ml = max( (i=1) - (start=-1)), ml=1) = 2


  1. class Solution {  
  2. public:  
  3.     int longestValidParentheses(string s) {  
  4.         stack<int> ss;  
  5.         int max = 0;  
  6.         //1、通過記錄匹配括號的位置資訊,來確認當前有效字串的最大長度
  7.         //(由於記錄了更多資訊,所以能力更強)
  8.         //2、當棧為空時,表示匹配至此處的整個字串有效。
  9.         int t;  
  10.         forint i= 0; i< s.size() ; i++){  
  11.             if( s[i] == ')' && !ss.empty() && s[ss.top()] == '('){  
  12.                 ss.pop();  
  13.                 if( ss.empty())  
  14.                     max = i+1;  
  15.                 else
  16.                     //記錄當前子串有效長度
  17.                     if( i - ss.top() > max)  
  18.                         max = i - ss.top();  
  19.             }  
  20.             else
  21.                 ss.push(i);  
  22.         }  
  23.         return max;  
  24.     }  
  25. };