leetcode Longest Valid Parentheses

来源:互联网 发布:js获取子节点多一个 编辑:程序博客网 时间:2024/06/07 14:18

Longest Valid Parentheses

 Total Accepted: 4153 Total Submissions: 22587My Submissions

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.


每次操作栈和其他容器的时候都要注意是否为空。

这道题的计算要注意,如何才能得到当前最长valid parentheses。

int longestValidParentheses(string s) {stack<int> stk;int len = 0;for (int i = 0; i < s.length(); i++){if (s[i] == '(') stk.push(i);else{if (stk.empty()) stk.push(i);else{if (s[stk.top()] == '('){stk.pop();if (stk.empty()) len = max(len, i+1);else len = max(len, i-stk.top());}else stk.push(i);}}}return len;}

巧妙地利用栈,保留下标,然后根据条件判断,逐步计算出结果。

分支条件有三到四个,也挺容易出错的题目。

[cpp] view plaincopyprint?
  1. class Solution {  
  2. public:  
  3.     int longestValidParentheses(string s)   
  4.     {  
  5.         int n = s.length();  
  6.         stack<int> stk;  
  7.         int longestLen = 0;  
  8.         for (int i = 0; i < n; i++)  
  9.         {  
  10.             if (s[i] == '(') stk.push(i);  
  11.             else  
  12.             {  
  13.                 if (stk.empty())  
  14.                 {  
  15.                     stk.push(i);  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     if (s[stk.top()] != '(')  
  20.                         stk.push(i);  
  21.                     else  
  22.                     {  
  23.                         stk.pop();  
  24.                         //居然会漏了max写成maxLen = (maxLen, i+1)  
  25.                         if (stk.empty()) longestLen = max(longestLen, i+1);  
  26.                         else    longestLen = max(longestLen, i-stk.top());  
  27.                     }  
  28.                 }  
  29.             }  
  30.         }  
  31.         return longestLen;  
  32.     }  
  33. };  



1 0
原创粉丝点击