标签:
将所有合法的括号即一对()都消除,用桟保存其中不合法的括号即单个(或)在字符串中的下标。那么每两个不合法之间的下标之差减1就是中间的合法串长度,依次从后向前比较,选出最大的字符串。
1 class Solution { 2 public: 3 int longestValidParentheses(string s) { 4 stack<int> st; 5 int n=s.length(),a,b,longest=0; 6 for(int i=0;i<n;i++) 7 { 8 if(s[i]==‘(‘)st.push(i); 9 else if(!st.empty()) //当桟为空时,它的top为0,故要判断一下是否为空 10 { 11 if(s[st.top()]==‘(‘)st.pop(); 12 else st.push(i); 13 } 14 else st.push(i); 15 16 } 17 a=n; 18 b=0; 19 if(st.empty())longest=n; 20 else 21 { 22 while(!st.empty()) 23 { 24 b=st.top();st.pop(); 25 longest=max(longest,a-b-1); 26 a=b; 27 } 28 longest=max(longest,a); 29 } 30 return longest; 31 } 32 };
下面的是动态规划求法:
每个longest表示此段的最有效长度,以‘)’进行划分
1 class Solution { 2 public: 3 int longestValidParentheses(string s) { 4 int n=s.length(); 5 int maxValid=0; 6 vector<int> longest(n,0); 7 for(int i=1;i<n;i++) 8 { 9 if(s[i]==‘)‘) 10 { 11 if(s[i-1]==‘(‘) 12 { 13 longest[i]=(i-2)>=0? (longest[i-2]+2):2; 14 maxValid=max(maxValid,longest[i]); 15 } 16 else if((i-longest[i-1]-1)>=0&&s[i-longest[i-1]-1]==‘(‘) //i-longest[i-1]-1 是求与这个‘(’相对应的‘(’位置 17 { 18 longest[i]=longest[i-1]+2+((i-longest[i-1]-2>=0)?longest[i-longest[i-1]-2]:0); // 注意最后的一个大括号,不能丢!! 19 maxValid=max(maxValid,longest[i]); 20 } 21 } 22 } 23 return maxValid; 24 } 25 };
标签:
原文地址:http://www.cnblogs.com/daocaorenblog/p/4903497.html