[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 '(', ')', '{', '}', '[ ...
随机推荐
- lstm公式推导
http://blog.csdn.net/u010754290/article/details/47167979 导言 在Alex Graves的这篇论文<Supervised Sequence ...
- app后端开发系列文章文件夹
一点废话 每个程序猿心中,都有一个大牛梦.我们在晨曦之光中敲击着代码,在寒冬覆雪中思考着0与1. 夏练三伏 冬练三九这说的就是我们这群[江湖]中人.在这里我们门派林立,C语言派历史悠久,在程序界就是嵩 ...
- Leet Code OJ 338. Counting Bits [Difficulty: Medium]
题目: Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate ...
- 每天一个 Linux 命令(16):which whereis locate命令
which 查看可执行文件的位置. whereis 查看文件的位置. locate 配合数据库查看文件位置.#whereis 和locate是从文件数据库里查找 数据库默认一个星期更新一次,所有 ...
- 每天进步一点点——mysql——Percona XtraBackup(innobackupex)
一. 简单介绍 Percona XtraBackup是开源免费的MySQL数据库热备份软件,它能对InnoDB和XtraDB存储引擎的数据库非堵塞地备份(对于MyISAM的备份相同须要加表锁).Xt ...
- Toad 使用中遇到的问题
1:智能提示: 视图-->toad选项-->Editor-->Code Assist-->Toad Insight---->sort pick list alphabet ...
- 笔记08 throw e 和throw 的区别
throw e对原异常进行拷贝,然后将新的异常对象抛出,这一步拷贝就有可能导致错误啦,拷贝出来的异常对象可能和原来的异常对象不是一个类型. 比如原来的对象是个子类的异常对象,catch里声明的是父类异 ...
- systemd、upstart和system V
http://blog.csdn.net/kumu_linux/article/details/7653802 systemd是Linux下的一种init软件,由Lennart Poettering ...
- 压力测试工具ab,wrk,locust简介
ab 无疑是目前最常见的压力测试工具.其典型用法如下: shell> ab -k -c 100 -t 10 http://domain/path 其中,参数「c」表示的是并发, 参数「t」表示的 ...
- linux下修改主机名hostname方法(转载)
查看主机名: 在终端输入hostname 永久修改 第一步:#hostname oratest 第二步:修改/etc/sysconfig/network中的hostname 第三步:修改/etc/ho ...