随笔- 509  文章- 0  评论- 151  阅读- 22万 

Longest Valid Parentheses

2014.2.13 02:32

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.

Solution:

  First of all, if you use a stack to simulate the push() and pop() operations with '(' and ')', you'll always get an empty stack at the end if the sequence is valid.

  My first reaction on this problem is an O(n^2) solution by dynamic programming. Apparently it's for subsequence, not substring, as substring is consecutive. Later I thought about O(n) dynamic programming, but no good idea came to me.

  When I tried to use a stack to simulate the sequence, I realized that the thing I pushed into the stack don't have to be the same '(', but their index.

  With the index of '(' recorded in the stack, whenever a matching with ')' happened, I can calculate the length of that matching sequence.

  The algorithm is online and one-pass, with the help of a stack and O(1) amount of extra parameters.

  Total time complexity is O(n). Space complexity is O(n) as well.

Accepted code:

复制代码
 1 // 1WA, 1AC, the simpliest solution is also the best one here.
 2 #include <algorithm>
 3 #include <stack>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int longestValidParentheses(string s) {
 9         stack<int> st;
10         int i, len;
11         int last_pos;
12         int max_res;
13         
14         last_pos = -1;
15         max_res = 0;
16         len = (int)s.length();
17         for (i = 0; i < len; ++i) {
18             if (s[i] == '(') {
19                 st.push(i);
20             } else if (s[i] == ')') {
21                 if (st.empty()) {
22                     last_pos = i;
23                 } else {
24                     st.pop();
25                     if (st.empty()) {
26                         max_res = max(max_res, i - last_pos);
27                     } else {
28                         max_res = max(max_res, i - st.top());
29                     }
30                 }
31             }
32         }
33         while (!st.empty()) {
34             st.pop();
35         }
36         
37         return max_res;
38     }
39 };
复制代码

 

 posted on   zhuli19901106  阅读(230)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示