[LeetCode] Longest Valid Parentheses -- 挂动态规划羊头卖stack的狗肉
(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的狗肉的更多相关文章
- [LeetCode] Longest Valid Parentheses 动态规划
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [LeetCode] Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [Leetcode] longest valid parentheses 最长的有效括号
Given a string containing just the characters'('and')', find the length of the longest valid (well-f ...
- [LeetCode] Longest Valid Parentheses 解题思路
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [LeetCode] Longest Valid Parentheses
第一种方法,用栈实现,最容易想到,也比较容易实现,每次碰到‘)’时update max_len,由于要保存之前的‘(’的index,所以space complexity 是O(n) // 使用栈,时间 ...
- LeetCode: Longest Valid Parentheses 解题报告
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- leetcode: Longest Valid Parentheses分析和实现
题目大意:给出一个只包含字符'('和')'的字符串S,求最长有效括号序列的长度. 很有趣的题目,有助于我们对这种人类自身制定的规则的深入理解,可能我们大多数人都从没有真正理解过怎样一个括号序列是有效的 ...
- leetcode Longest Valid Parentheses python
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype ...
- LeetCode之“动态规划”:Valid Parentheses && Longest Valid Parentheses
1. Valid Parentheses 题目链接 题目要求: Given a string containing just the characters '(', ')', '{', '}', '[ ...
随机推荐
- TensorFlow 之 高层封装slim,tflearn,keras
tensorflow资源整合 使用原生态TensorFlow API来实现各种不同的神经网络结构.虽然原生态的TensorFlow API可以很灵活的支持不同的神经网络结构,但是其代码相对比较冗长,写 ...
- procomm plus
procomm plus这是查看串口数据的软件.
- [c++菜鸟]《Accelerate C++》习题解答
第0章 0-0 编译并运行Hello, world! 程序. #include <iostream> using namespace std; int main() { cout < ...
- PS 基础知识 .atn文件如何使用
ANT文件就是Frames.atn类动作文件 具体安装步骤如下 : (以CS4 为例) 启动Photoshop 点击"窗口" 选"动作" 在弹出的动作面板里,点 ...
- 怎样高效利用GitHub(非常多资料可供下载)
正是Github.让社会化编程成为现实.本文尝试谈谈GitHub的文化.技巧与影响. Q1:GitHub是什么 Q2:GitHub风格 Q3: 在GitHub.怎样跟牛人学习 Q4: 享受纯粹的写作与 ...
- selector的button选中处理问题
1.背景介绍 在做Android项目开发的时候,有时我们须要对button做一些特殊的处理,比方button点击的时候会有一个动画的效果,实际上就是几张图片在短时间的切换.再比方有时候我们须要对界面的 ...
- 测试 MD
上面是一张图片 总店?
- win7自带照片查看器
win10如何找回自带的照片查看器 方法/步骤 1 首先,我们打开一个记事本,可以点击win+r打开运行框,然后在运行框中输入notepad.或者在桌面右键点击里面的新建,然后在新建中找到文本 ...
- Spring AOP(转载)
此前对于AOP的使用仅限于声明式事务,除此之外在实际开发中也没有遇到过与之相关的问题.最近项目中遇到了以下几点需求,仔细思考之后,觉得采用AOP 来解决.一方面是为了以更加灵活的方式来解决问题,另一方 ...
- commons.cli.jar 作用
对命令行进行处理的jar包.处理的步骤主要包括定义.分析和询问.(There are three stages to command line processing. They are the def ...