【LeetCode】Longest Valid Parentheses

来源:互联网 发布:岁月神偷 网络歌手 编辑:程序博客网 时间:2024/06/13 04:01

题目描述:

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.

我觉得我脑袋真是不会转弯……这题目想了挺久的……

对每个i进行扫描找到以i为起点的最长合法字符串然后比较当然是可行的,但是O(n^2)复杂度。

这题目一看就有O(n)的解法。一开始想的很复杂,思路是扫描整个字符串,对每个字符做if else处理,用count记录下之前'('的数目,每遇到一个')'长度++。但是这样没法有效分割合法字符串,例如遇到"(()(((()(((()(()"的时候会需要不定数目的变量来记录前个合法字符串的长度,不太好解。

后来想到的解法是这样的,用vector<bool> 来记录某位置字符是否是合法字符串的成员。用一个栈,每遇到一个'('就将index进栈,遇到')'时该位置记录为true,同时出栈并将出栈位置标记为true。最后生成的就是一个01组成的显而易见的数组了。

代码如下:

class Solution {public:int longestValidParentheses(string s) {stack<int> left;vector<bool> dist(s.length(), false);int res(0);for (int i = 0; i < s.length(); i++){if (s[i] == '(')left.push(i);else if (!left.empty()){dist[i] = true;dist[left.top()] = true;left.pop();}}int count(0);for (int i = 0; i < dist.size(); i++){if (dist[i]){count++;res = max(res, count);}elsecount = 0;}return res;}};


0 0
原创粉丝点击