leetcode: Longest Valid Parentheses

http://oj.leetcode.com/problems/longest-valid-parentheses/

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.

思路

当某个'('被')'匹配后,需要加上它左边已经匹配好的括号对长度。以"()(()()"举例,我们需要用一个stack来记录每个'('左边匹配好的括号对长度和对应的最左边'('的位置:

  1. '(':左边以匹配括号串长度为0,压入堆栈(0, 0),第一个0是位置,第二个0是左边以匹配括号串长度。
  2. ')':匹配第0个位置上的'(',长度为2,同时因为堆栈不为空,弹出堆栈顶部元素,2 + 0 (第0个'('左边以匹配括号串长度) = 2。
  3. '(':左边以匹配括号串长度为2,压入堆栈(2, 2),同时把左边以匹配括号串长度清0。
  4. '(':左边以匹配括号串长度为0,压入堆栈(3, 0)。此时堆栈从底到顶为((2, 2), (3, 0))。
  5. ')':匹配第3个位置上的'(',长度为2,同时因为堆栈不为空,弹出堆栈顶部元素,2 + 0 (第3个'('左边以匹配括号串长度) = 2。
  6. '(':左边以匹配括号串长度为2,压入堆栈(5, 2),同时把左边以匹配括号串长度清0。
  7. ')':匹配第5个位置上的'(',长度为2,同时因为堆栈不为空,弹出堆栈顶部元素,2 + 2 (第5个'('左边以匹配括号串长度) = 4。所以最后能匹配的最长括号串长度为4。
 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4         int max_len = 0, existing_len = 0;
 5         stack<pair<int, int> > records; // left par index, existing_len
 6         stack<int> left_pars;
 7         
 8         for (int i = 0; i < s.length(); ++i) {
 9             if ('(' == s[i]) {
10                 records.push(pair<int, int>(i, existing_len));
11                 existing_len = 0;
12             }
13             else {
14                 existing_len = 0;
15                 
16                 if (records.size() > 0) {
17                     pair<int, int> last = records.top();
18                     records.pop();
19                     
20                     existing_len = i - last.first + 1 + last.second;
21                     if (existing_len > max_len) {
22                         max_len = existing_len;
23                     }
24                 }
25             }
26         }
27         
28         return max_len;
29         
30     }
31 };

 

posted @ 2013-10-31 17:34  移山测试工作室黑灯老师  阅读(371)  评论(0编辑  收藏  举报
count website visits
Buy Computers