Valid Parentheses

Given a string containing just the characters '(', ')''{''}''[' and ']', determine if the input string is valid.

Example

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的更多相关文章

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

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

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

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

  3. Longest Valid Parentheses

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

  4. leetcode 32. Longest Valid Parentheses

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

  5. 【leetcode】Longest Valid Parentheses

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

  6. 【leetcode】 Longest Valid Parentheses (hard)★

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

  7. Longest Valid Parentheses 每每一看到自己的这段没通过的辛酸代码

    Longest Valid Parentheses My Submissions Question Solution  Total Accepted: 47520 Total Submissions: ...

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

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

  9. Java for LeetCode 032 Longest Valid Parentheses

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

随机推荐

  1. Software-Defined Networking:A Comprehensive Survey--Day1

    Software-Defined Networking:A Comprehensive Survey 摘要: 传统网络复杂且难以管理,根据预定义策咯也难以对网络进行配置,也难以重新配置. 软件定义网络 ...

  2. 第八周PSP(11.5--11.9)

    2016.11.5 2016.11.6 2016.11.7 2016.11.8 2016.11.9

  3. Python爬虫:学爬虫前得了解的事儿

    这是关于Python的第14篇文章,主要介绍下爬虫的原理. 提到爬虫,我们就不得不说起网页,因为我们编写的爬虫实际上是针对网页进行设计的.解析网页和抓取这些数据是爬虫所做的事情. 对于大部分网页来讲, ...

  4. PAT 甲级 1115 Counting Nodes in a BST

    https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904 A Binary Search Tree ( ...

  5. asp、asp.net、.aspx、.ascx、.ashx的简单说明

    ASP是动态server页面(Active Server Page)的英文缩写.[1]是微软公司开发的取代CGI脚本程序的一种应用.它能够与数据库和其他程序进行交互,是一种简单.方便的编程工具.ASP ...

  6. CentOS75 安装 telnet 进行使用.

    1. 安装必须要的服务 yum install xinetd telnet telnet-server 2. 修改增加root用户登录权限 vi /etc/securetty 在最后面增加两行 pts ...

  7. python315题

    目录 Python基础篇 1:为什么学习Python 2:通过什么途径学习Python 3:谈谈对Python和其他语言的区别 Python的优势: 4:简述解释型和编译型编程语言 5:Python的 ...

  8. Two Bases CodeForces - 602A (BigInteger c++long long也可以)

    哇咔咔 卡函数的 标记一下 c++和java的进制转换函数都是1-36进制的 c++ long long暴力就过了... 自己写一个就好了 import java.math.BigInteger; i ...

  9. 牛客网暑期ACM多校训练营(第二场)J farm (二维树状数组)

    题目链接: https://www.nowcoder.com/acm/contest/140/J 思路: 都写在代码注释里了,非常好懂.. for_each函数可以去看一下,遍历起vector数组比较 ...

  10. hdu5583

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> ...