Valid Parentheses & Longest Valid Parentheses
Valid Parentheses
Given a string containing just the characters '(', ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
分析:
使用stack来保存每个括号,如果最上面的和当前括号匹配,则除去最上面的括号,否则把新括号加入。如果最后stack为空,则所有括号匹配。
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
if (s == null || s.length() % == ) return false;
Stack<Character> stack = new Stack<Character>(); for (int i = ; i < s.length(); i++) {
if (stack.size() == ) {
stack.push(s.charAt(i));
} else {
char c1 = stack.peek();
char c2 = s.charAt(i);
if (c1 == '(' && c2 == ')' || c1 == '[' && c2 == ']' || c1 == '{' && c2 == '}') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
}
return stack.isEmpty();
}
}
Longest Valid Parentheses
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.
The idea from https://leetcode.com/problems/longest-valid-parentheses/discuss/14126/My-O(n)-solution-using-a-stack
The workflow of the solution is as below.
1. Scan the string from beginning to end. If current character is '(', push its index to the stack. If current character is ')' and the
character at the index of the top of stack is '(', we just find a
matching pair so pop from the stack. Otherwise, we push the index of
')' to the stack.
2. After the scan is done, the stack will only
contain the indices of characters which cannot be matched. Then
let's use the opposite side - substring between adjacent indices
should be valid parentheses.
3. If the stack is empty, the whole input
string is valid. Otherwise, we can scan the stack to get longest
valid substring as described in step 3.
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> st = new Stack<>();
for (int i = ; i < s.length(); i++) {
if (s.charAt(i) == '(') {
st.push(i);
} else {
if (st.empty()) {
st.push(i);
} else if (s.charAt(st.peek()) == '(') {
st.pop();
} else {
st.push(i);
}
}
}
int longest = , end = s.length(); while (!st.empty()) {
int start = st.pop();
longest = Math.max(longest, end - start - );
end = start;
}
return Math.max(longest, end);
} }
Another DP solution (https://leetcode.com/problems/longest-valid-parentheses/discuss/14133/My-DP-O(n)-solution-without-using-stack) is also very good. Here is the idea:
First, create an array longest[], for any longest[i], it stores the longest length of valid parentheses which ends at i.
And the DP idea is :
If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.
Else if s[i] is ')'
If s[i-1] is '(', longest[i] = longest[i-2] + 2
Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
int longestValidParentheses(String s) {
if (s.length() <= ) {
return ;
}
int curMax = ;
int[] longest = new int[s.length()];
for (int i = ; i < s.length(); i++) {
if (s.charAt(i) == ')') {
if (s.charAt(i - ) == '(') {
longest[i] = (i - ) >= ? longest[i - ] + : ;
curMax = Math.max(longest[i], curMax);
} else {
int indexBeforeMatching = i - longest[i - ] - ;
if (indexBeforeMatching >= && s.charAt(indexBeforeMatching) == '(') {
longest[i] = longest[i - ] + + ((i - longest[i - ] - >= ) ? longest[i - longest[i - ] - ] : );
curMax = Math.max(longest[i], curMax);
}
}
}
// else if s[i] == '(', skip it, because longest[i] must be 0
}
return curMax;
}
Valid Parentheses & Longest Valid Parentheses的更多相关文章
- LeetCode之“动态规划”:Valid Parentheses && Longest Valid Parentheses
1. Valid Parentheses 题目链接 题目要求: Given a string containing just the characters '(', ')', '{', '}', '[ ...
- [LeetCode] Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- leetcode 32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【leetcode】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- 【leetcode】 Longest Valid Parentheses (hard)★
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Longest Valid Parentheses 每每一看到自己的这段没通过的辛酸代码
Longest Valid Parentheses My Submissions Question Solution Total Accepted: 47520 Total Submissions: ...
- [LeetCode] Longest Valid Parentheses 动态规划
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Java for LeetCode 032 Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
随机推荐
- 《Linux内核分析》第四周学习笔记
<Linux内核分析>第四周学习笔记 扒开系统调用的三层皮(上) 郭垚 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.c ...
- Python 四种数值类型(int,long,float,complex)区别及转换
Python支持四种不同的数值类型,包括int(整数)long(长整数)float(浮点实际值)complex (复数), 数字数据类型存储数值.他们是不可改变的数据类型,这意味着改变数字数据类型的结 ...
- struts2中的方法的调用
转载:http://blog.csdn.net/hephec/article/details/41808585 在Struts2中方法调用概括起来主要有三种形式: 第一种方式:指定method属性 & ...
- java 封装,继承,多态基础
什么是封装? 1,对象数据和在.操作该对象的指令都是对象自身的一部分,能够实现尽可能对外部隐藏数据. 2,实际项目开发中,使用封装最多的就是实体类. 什么是继承? 1,继承是面向对象程序设计能提高效率 ...
- idea不能跟随输入法问题
在写注释的时候会发现输入法不跟随,这是idea工具本身存在的bug,这个问题很头疼,我找了好多办法都不行,比如删除idea自带的jre,这个办法对我的2018.1.5版本并不适用,以下办法是不需要删除 ...
- Delphi cxGrid加行号
procedure SetRowNumber(var ASender: TcxGridTableView; AViewInfo: TcxCustomGridIndicatorItemViewInfo; ...
- C#快速删除bin和obj文件夹的方法
C#程序总会生成bin和obj文件夹,为了减小源码的大小,就有必要将这两个文件夹删除,于是想到用批处理文件来删除. 以下是批处理的代码: @echo offset nowPath=%cd%cd /cd ...
- Go匿名函数
1.GO语言的匿名函数就是闭包 基本概念 闭包是可以包含自由(未绑定到特定对象)变量的代码块,这些变量不在这个代码块内或者任何全局上下文中定义,而是在定义代码块的环境中定义.要执行的代码块(由于自由变 ...
- Eclipse 使用 VS快捷键
这里楼主也是尝试了,只能说一般吧.还是有许多没有改过来... 想要尝试的朋友,可以试试. 首先进入Eclipse 然后 接着 Name:CDT Location:http://download.ecl ...
- 51nod 1463 找朋友 (扫描线+线段树)
1463 找朋友 基准时间限制:1.5 秒 空间限制:262144 KB 分值: 80 难度:5级算法题 收藏 关注 给定: 两个长度为n的数列A .B 一个有m个元素的集合K 询问Q次 每次询 ...