Valid Parentheses & Longest Valid Parentheses

时间:2022-04-08 22:49:31

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之&OpenCurlyDoubleQuote;动态规划”:Valid Parentheses &amp&semi;&amp&semi; Longest Valid Parentheses

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

  2. &lbrack;LeetCode&rsqb; 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&period; 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 &lpar;hard&rpar;&starf;

    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. &lbrack;LeetCode&rsqb; 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. LruCache为GridView异步加载大量网络图片

    MainActivity如下: import android.os.Bundle; import android.widget.GridView; import android.app.Activit ...

  2. Activiti系列:是否可以让某些流程的信息写到历史表,而另外一些不写?

    一.起因     打算使用activiti的定时启动事件来定时启动流程,然后再在该流程中针对每个用户启动另外一个流程实例来计算每个用户的实时账单,系统的用户数一般是1000~2000(此处假设是200 ...

  3. boot&period;img的分析

    1 boot.img  boot.img是由文件头信息,内核数据以及文件系统数据组成,它们之间非页面对齐部分用0填充 文件头信息的具体结构可以在system/core/mkbootimg/bootim ...

  4. &lbrack;学习整理&rsqb;eclipe&sol;MyEclipse:重要的快捷键

    一.查看大工程代码最重要的几个快捷键 其实有一些,直接在编辑器页面内右键也可查看相应的快捷键(比如F3,F4,Ctrl+O,Ctrl+T),但有些比较好用的快捷键,并不能能直接或方便地在eclipse ...

  5. c语言所有的errno枚举值含义

    可以通过以下代码,获取所有的错误码信息: #include <string.h> /* for strerror */ #include <errno.h> #include ...

  6. BZOJ 1631&colon; &lbrack;Usaco2007 Feb&rsqb;Cow Party&lpar; 最短路 &rpar;

    这道题和蔡大神出的今年STOI初中组的第二题几乎一模一样... 先跑一遍最短路 , 再把所有边反向 , 再跑一遍 , 所有点两次相加的最大值即为answer --------------------- ...

  7. Kafka 0&period;10 Metadata的补充

    什么是Metadata? Topic/Partion与broker的映射关系:每一个Topic的每一个Partion的Leader.Follower的信息. 它存在哪里?持久化在Zookeeper中: ...

  8. JDK的安装及环境变量配置

    JDK的安装及环境变量配置 JDK解释:直达详细解释. 1.JDK下载地址:点击直达官网下载 进入后,如图1,点击图中红框DOWNLOAD按钮进入下载页 进入下载页后,在下载也底端,根据自己的需求下载 ...

  9. 【转】Linux netstat命令详解&comma;高级面试必备

    简介 Netstat 命令用于显示各种网络相关信息,如网络连接,路由表,接口状态 (Interface Statistics),masquerade 连接,多播成员 (Multicast Member ...

  10. mui 窗口管理及窗口之间的数据传递

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...