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. Day Eight

    站立式会议 站立式会议内容总结 331 今天:学习树状自关联 hibernate配置,查询 详情:http://blog.csdn.net/u011644423/article/details/498 ...

  2. 阅读c#程序——回答问题

    c#“小”程序: using System; using System.Collections.Generic; using System.Text; namespace FindTheNumber ...

  3. 第三周(JAVA编写的 wordcount)

    import java.io.*; public class WordCount { public static int words=1; public static int lines=1; pub ...

  4. react-router JS 控制路由跳转(转载)

    Link组件用于正常的用户点击跳转,但是有时还需要表单跳转.点击按钮跳转等操作.这些情况怎么跟React Router对接呢? 下面是一个表单. <form onSubmit={this.han ...

  5. 11th 最后的致意

    “终于我们不再是师生”,无论日后我们是否是师生,但这段经历是不可否认的,可以说软件工程这一门课程恐怕是我学生生涯中终生难忘的一段体验.即便不是从知识上,从另一个方面来讲,也教给了我一种做人做事的态度. ...

  6. [转帖] Linux 创建一个简单的私有CA、发证、吊销证书

    原创帖子地址:   https://blog.csdn.net/mr_rsq/article/details/71001810 Linux 创建一个简单的私有CA.发证.吊销证书 2017年04月30 ...

  7. 2013长春网赛1009 hdu 4767 Bell(矩阵快速幂+中国剩余定理)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4767 题意:求集合{1, 2, 3, ..., n}有多少种划分情况bell[n],最后结果bell[ ...

  8. dubbo的spi机制

    SPI SPI是一种扩展机制,在java中SPI机制被广泛应用,比如Spring中的SpringServletContainerInitializer 使得容器启动的时候SpringServletCo ...

  9. 利用powerful number求积性函数前缀和

    好久没更博客了,先水一篇再说.其实这个做法应该算是杜教筛的一个拓展. powerful number的定义是每个质因子次数都 $\geq 2$ 的数.首先,$\leq n$ 的powerful num ...

  10. Python3中的编码问题

    编码方式介绍 我们首先来熟悉一下常见的一些编码方式,按照时间轴来划分,共有以下几种编码方式(常见): ASCII编码方式:对127个常见字符进行编码,其中包含了10个阿拉伯数字,共52个大小写英文字母 ...