(Version 1.3)

这题在LeetCode上的标签比较有欺骗性,虽然标签写着有DP,但是实际上根本不需要使用动态规划,相反的,使用动态规划反而会在LeetCode OJ上面超时。这题正确的做法应该和Largest Rectangle in Histogram那几个使用stack来记录并寻找左边界的题比较类似,因为在仔细分析问题并上手尝试解决时,会发现问题的关键在于怎么判定一个valid parentheses子串的起始位置,或者说当遇到一个')'时,怎么知道要加到哪里去。

第一次做的时候因为标签是DP,所以写了一个无脑版本的DP,时间复杂度是O(N^2)的,结果不出意料得到了Time Limit Exceeded,代码如下,

 public class Solution {
public int longestValidParentheses(String s) {
if (s.length() < 2) {
return 0;
}
int result = 0;
boolean[][] isValid = new boolean[s.length()][s.length()];
int len = s.length();
for (int i = 0; i < isValid.length - 1; i++) {
if (s.charAt(i) == '(' && s.charAt(i + 1) == ')') {
isValid[i][i + 1] = true;
result = 2;
}
}
for (int l = 4; l <= len; l += 2) {
int bound = len - l;
for (int i = 0; i <= bound; i++) {
int j = i + l - 1;
isValid[i][j] = (isValid[i + 1][j - 1] && s.charAt(i) == '(' && s.charAt(j) == ')')
|| (isValid[i][j - 2] && s.charAt(j - 1) == '(' && s.charAt(j) == ')')
|| (isValid[i + 2][j] && s.charAt(i) == '(' && s.charAt(i + 1) == ')');
if (isValid[i][j] && l > result) {
result = l;
}
}
}
return result;
}
}

于是忽然意识到这题既然是求substring而不是subsequence,没准可以不用DP来做,因为substring的话感觉好像并不会有很多overlapping的subproblem,而是可以不断地明确砍掉已经处理过的substring进而缩小问题范围,于是想到了依然采用类似Valid Parentheses的计数的方法,用O(N)的时间复杂度和O(1)的空间复杂度就可以解决,代码如下:

 public class Solution {
public int longestValidParentheses(String s) {
if (s.length() < 2) {
return 0;
}
int result = 0;
int count = 0;
int diff = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
count++;
diff++;
} else {
diff--;
if (diff < 0) {
diff = 0;
count = 0;
} else if (diff == 0 && result < (count << 1)) {
result = count << 1;
}
}
}
count = 0;
diff = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')') {
count++;
diff++;
} else {
diff--;
if (diff < 0) {
diff = 0;
count = 0;
} else if (diff == 0 && result < (count << 1)) {
result = count << 1;
}
}
}
return result;
}
}

其中用右移一位运算代替了乘2,纯属个人爱好,可能不是一个好的代码习惯。这个代买的思路是先从左向右走一次,每当发现所有在考虑的左右括号完全匹配(即diff == 0时)尝试更新result。第一次走下来如果左括号一直多于右括号的话就无法得到答案,所以再从右到左走一次,这样两次当中可以确保至少有一次能够使得diff == 0,以取得正确答案。

这一版本的答案是由于之前一直在思考DP的做法而产生的,如果向Valid Parentheses的解法靠拢尝试使用stack的话应该会有使用额外空间但是只需要扫一次的解法。

下面是重写的code ganker的解法(http://blog.csdn.net/linhuanmars/article/details/20439613),思路主要是:类似Valid Parentheses,用一个stack按顺序记录'('的index,再用一个变量记录当前可能的substring的开头。每当遇到一个')'时,若stack非空,则pop出一个元素,若pop之后非空,说明当前只能匹配到上一个尚未被匹配的'(',即stack.peek();若stack为空,说明可以一直匹配到start。当发现')'多于'('时,即在遇到')'时stack为空,则需要移动start到至少最后一个')'的下一位,因为易得当')'多于'('时,不可能再继续append到之前的任何substring得到依然valid的,所以可以砍掉前面的东西,缩小需要考虑的范围。代码如下:

 public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int result = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (!stack.isEmpty()) {
stack.pop();
result = stack.isEmpty() ? Math.max(result, i - start + 1) : Math.max(result, i - stack.peek());
} else {
start = i + 1;
}
}
} return result;
}
}

这个解法的关键insight在于理解用stack存index的真正目的是记录可能的substring左边界,用于在找到一个')'判断左边界应该在哪,值得集中练习掌握,LeetCode上面相关的题目还有上面提到的Largest Rectangle in Histogram,Trapping Rain Water等。

[LeetCode] Longest Valid Parentheses -- 挂动态规划羊头卖stack的狗肉的更多相关文章

  1. [LeetCode] Longest Valid Parentheses 动态规划

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. [LeetCode] Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  3. [Leetcode] longest valid parentheses 最长的有效括号

    Given a string containing just the characters'('and')', find the length of the longest valid (well-f ...

  4. [LeetCode] Longest Valid Parentheses 解题思路

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. [LeetCode] Longest Valid Parentheses

    第一种方法,用栈实现,最容易想到,也比较容易实现,每次碰到‘)’时update max_len,由于要保存之前的‘(’的index,所以space complexity 是O(n) // 使用栈,时间 ...

  6. LeetCode: Longest Valid Parentheses 解题报告

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  7. leetcode: Longest Valid Parentheses分析和实现

    题目大意:给出一个只包含字符'('和')'的字符串S,求最长有效括号序列的长度. 很有趣的题目,有助于我们对这种人类自身制定的规则的深入理解,可能我们大多数人都从没有真正理解过怎样一个括号序列是有效的 ...

  8. leetcode Longest Valid Parentheses python

    class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype ...

  9. LeetCode之“动态规划”:Valid Parentheses && Longest Valid Parentheses

    1. Valid Parentheses 题目链接 题目要求: Given a string containing just the characters '(', ')', '{', '}', '[ ...

随机推荐

  1. win7 32 c++环境

    http://jingyan.baidu.com/article/455a99509c76d8a1662778f6.html 首先我们先来到这个网址下载MinGW的下载程序,百度搜索官网即可.下载之后 ...

  2. java单测时的等待模块awaitility

    单测时,可以用来等待异步任务完成 在编写自动化测试用例过程中,往往会遇见被测代码有异步或者队列处理的中间过程:如果需要校验这部分结果,必须等待异步操作结束或队列消费完,而这个中间等待的时间是不确定的, ...

  3. Git以及github的使用方法(三),git status查看工作区的状态,git diff查看具体修改内容

    我们已经成功地添加并提交了一个readme.txt文件,现在,是时候继续工作了,于是,我们继续修改readme.txt文件,改成如下内容: Git is a distributed version c ...

  4. 我的Android进阶之旅------&gt;怎样解决Android 5.0中出现的警告: Service Intent must be explicit:

    我的Android进阶之旅-->怎样解决Android 5.0中出现的警告: java.lang.IllegalArgumentException: Service Intent must be ...

  5. 【每日Scrum】第七天(4.28)Sprint2总结性会议

    本次会议主要是演示了一下本组项目的各项功能,每个人负责那一块儿功能由本人来负责说明和演示,确定alpha版本的发布时间,并且分派了各组员的文档负责情况,上图是会议记录,下面我详细介绍一下我组分派情况: ...

  6. PHP开发环境简析

    单工作机情况 windows + wamp windows + XShell类终端工具 + linux虚拟机 Ubuntu桌面版 自带终端 Mac OS + mamp Mac OS 自带终端 Mac ...

  7. Android 设计模式之单例模式

    设计模式是前人在开发过程中总结的一些经验,我们在开发过程中依据实际的情况,套用合适的设计模式,能够使程序结构更加简单.利于程序的扩展和维护.但也不是没有使用设计模式的程序就不好.如简单的程序就不用了, ...

  8. ffmpeg mediacodec 硬解初探

    ffmpeg mediacodec 硬解初探 1编译: ffmpeg自3.1版本加入了android mediacodec硬解支持,解码器如图 硬件加速器如图(还不清楚硬件加速器的功能) 编译带h26 ...

  9. Scrapy爬虫入门系列2 示例教程

    本来想爬下http://www.alexa.com/topsites/countries/CN 总排名的,但是收费了 只爬了50条数据: response.xpath('//div[@class=&q ...

  10. iOS8中提示框的使用UIAlertController(UIAlertView和UIActionSheet二合一)

     本文转载至 http://blog.csdn.net/liuwuguigui/article/details/39494597       IOS8UIAlertViewUIActionSheet ...