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. Linux内核分析第一二章读书笔记

    linux读书笔记(1,2章) 标签(空格分隔): 20135328陈都 第一章 Linux内核简介 Unix的历史 Unix 虽然已经使用了40年,但计算机科学家仍然认为它是现存操作系统中最强大和最 ...

  2. Leetcode题库——36.有效的数独

    @author: ZZQ @software: PyCharm @file: leetcode36_isValidSudoku.py @time: 2018/11/19 19:27 要求:判断一个 9 ...

  3. 祝贺自己操作系统JAVA项目有进展!!

    先公布研发过程的心得吧!!! ^_^ /** * 作者:范铭祥 * 内容及功能: 显示框创造1.0 * 我将在这个类里 一:面板1:用来先显示一副图表示顺序和处理中 * 二:面板2:类1:用来显示要处 ...

  4. [软工课程博客] 求解第N个素数

    任务 求解第 10,0000.100,0000.1000,0000 ... 个素数(要求精确解). 想法 Sieve of Eratosthenes 学习初等数论的时候曾经学过埃拉托斯特尼筛法(Sie ...

  5. [UWP 开发] 一个简单的Toast实现

    Toast简介 在安卓里Toast是内置原生支持,它是Android中用来显示显示信息的一种机制.它主要用于向用户显示提示消息,没有焦点,显示的时间有限,过一定的时间就会自动消失.在UWP中虽然没有原 ...

  6. 从零开始学Kotlin-类和对象(5)

    定义一个类 定义一个类,使用关键字class声明,后面跟类名(不使用new) class demo5 {//定义一个类,使用关键字class声明,后面跟类名 fun test() {//类中定义方法 ...

  7. 群里提到的IE设置问题 ---B/S 下页面刷新问题

    这里面四个选项的含义 下面是每个选项的作用和意义: 1. “每次访问此页时检查”选项表示浏览器每次访问一个页面时,不管浏览器是否缓存过此页面,都要向服务器发出访问请求.这种设置的优点是实时性很强,肯定 ...

  8. mysql 好用的sql语句

    1.删除某个库里面全部的表 ,先在mysql库中执行:  SELECT CONCAT('drop table ',table_name,';') FROM information_schema.`TA ...

  9. 点分治&动态点分治小结

    (写篇博客证明自己还活着×2) 转载请注明原文地址:http://www.cnblogs.com/LadyLex/p/8006488.html 有的时候,我们会发现这样一类题:它长得很像一个$O(n) ...

  10. nginx “403 Forbidden” 错误的原因及解决办法

    nginx 的 403 Forbidden errors 表示你在请求一个资源文件但是nginx不允许你查看. 403 Forbidden 只是一个HTTP状态码,像404,200一样不是技术上的错误 ...