编程之美---最长有效括号字串

题目

         给定字符串,仅包含左括号‘(’和右括号‘)’,它可能不是括号匹配的,设计算法,找出最长匹配的括号子串,返回该子串的长度。

         如:

                  (():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. };  


你可能感兴趣的:(编程之美)