From f306cb33328aeae344accf4d6adf8dd059ca6294 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Thu, 26 Mar 2020 20:38:12 +0800 Subject: [PATCH] add q32 --- .idea/workspace.xml | 79 ++++++++----------- README.md | 1 + .../q32_最长有效括号/Solution.java | 38 +++++++++ 3 files changed, 72 insertions(+), 46 deletions(-) create mode 100644 src/栈相关/q32_最长有效括号/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index d5780ba..3fb544b 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,8 +2,7 @@ - - + @@ -64,7 +63,7 @@ - + @@ -81,20 +80,7 @@ - - - + - - @@ -290,14 +276,8 @@ - - - - 1580395653122 - 1580409713059 @@ -635,7 +615,14 @@ - @@ -688,7 +675,6 @@ - @@ -713,7 +699,8 @@ - @@ -728,35 +715,35 @@ - + - + - + - + - + - + - + - + - + - + @@ -782,14 +769,14 @@ - + - - + + - + diff --git a/README.md b/README.md index f97f646..a80a1f7 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ ### 栈相关 * [q20_有效的括号](/src/栈相关/q20_有效的括号) +* [q32_最长有效括号](/src/栈相关/q32_最长有效括号) * [q224_基本计算器](/src/栈相关/q224_基本计算器) * [q316_去除重复字母](/src/栈相关/q316_去除重复字母) diff --git a/src/栈相关/q32_最长有效括号/Solution.java b/src/栈相关/q32_最长有效括号/Solution.java new file mode 100644 index 0000000..bd07506 --- /dev/null +++ b/src/栈相关/q32_最长有效括号/Solution.java @@ -0,0 +1,38 @@ +package 栈相关.q32_最长有效括号; + +import java.util.Stack; + +/** + * 利用索引栈 o(n) + */ +public class Solution { + + public int longestValidParentheses(String s) { + if (s == null || s.length() < 2) { + return 0; + } + + int maxLen = 0; + Stack stack = new Stack<>(); + stack.push(-1); + for (int i = 0; i < s.length(); i++) { + char temp = s.charAt(i); + if (temp == '(') { + stack.push(i); + } else { + stack.pop(); + if (stack.empty()) { + stack.push(i); + } else { + maxLen = Math.max(maxLen, i - stack.peek()); + } + } + } + + return maxLen; + } + + public static void main(String[] args) { + System.out.println(new Solution().longestValidParentheses(")()())")); + } +}