32. Longest Valid Parentheses
来源:互联网 发布:壹品曹户型优化 编辑:程序博客网 时间:2024/05/22 02:14
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.
确实挺难的
一开始的想法是这样的 一个有效的字符串肯定是以”(“开头的 那么就从每个”(“开始 遇到”(“就push进stack
遇到”)” 分两种情况
1.stack如果是空的 说明没有对应的”(“ 目前为止的字符串无效 长度归零
2.如果stack不为空就pop一个”(“出来 长度+2
过程中求最大长度 比如输入是 “()((()))”
我们用i代表扫描的位置
当i=1时 len=2
i=2,3,4时 因为没有对应的”)” len=2
i=5,6,7 len分别对应4,6,8
代码如下
public int longestValidParentheses(String s) { Stack<Character> stack = new Stack<>(); int local = 0, len = 0; for (char c : s.toCharArray()) { switch (c) { case '(': stack.push(c); break; case ')': if (!stack.isEmpty()) { stack.pop(); local+=2; len = Math.max(len, local); } else { local = 0; } break; } } return len; }
乍一看没什么问题 但是当输入是”()((()”时呢
返回结果是4 而不是2
因为我只判断了”)”无效的情况 长度会归零
没有判断”("无效的情况 也就是”(“没有对应的”)”的情况 也应该长度归零
而且也没有必要用stack 用left记录”(“的个数 用right记录”)”的个数 当left == right len+=2*left就可以了
那该怎么修改呢 再从右到左扫描一遍
public class Solution { public int longestValidParentheses(String s) { int left = 0, right = 0, maxlength = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * right); } else if (right >= left) { left = right = 0; } } left = right = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * left); } else if (left >= right) { left = right = 0; } } return maxlength; }}
阅读全文
0 0
- 32.Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 操作系统中 heap 和 stack 的区别
- 进程基础知识
- sed awk文本处理教程
- F盘提示文件系统损坏数据怎样寻回
- PAL,NTSC,分辨率,清晰度和电视线解析
- 32. Longest Valid Parentheses
- 集算器-各类别产品库存量统计情况随机抽检
- 关于VS控制台输出中文乱码问题
- Server Tomcat v8.0 Server at localhost failed to start
- Android Study Material Design 十五 深入Behavior以及自定义Behavior
- python编程入门
- UITableViewCell编辑效果
- JS学习总结(一)
- 信息学奥赛一本通(C++版) 第三部分 数据结构 第三章 树