LeetCode -- Longest Valid Parentheses
来源:互联网 发布:python wind 15分钟 编辑:程序博客网 时间:2024/06/11 08:11
题目描述:
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.
思路:
1.遍历s[i] ,i∈[0,n)并使用stack存当前索引i
2.如果s[i] 为 ')' 且stack不为空 且s[stack.Peek()] 为'('
:stack弹出
如果stack为空 , max = i + 1
否则,max = Max(max,i-stack.Peek())
否则(即s[i]为'('),直接将s[i]入栈
实现代码:
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.
思路:
1.遍历s[i] ,i∈[0,n)并使用stack存当前索引i
2.如果s[i] 为 ')' 且stack不为空 且s[stack.Peek()] 为'('
:stack弹出
如果stack为空 , max = i + 1
否则,max = Max(max,i-stack.Peek())
否则(即s[i]为'('),直接将s[i]入栈
实现代码:
public class Solution { public int LongestValidParentheses(string s) { int max = 0; var stack = new Stack<int>(); for (int i = 0; i < s.Length; i++) { if (s[i] == ')' && stack.Count > 0 && s[stack.Peek()] == '(') { stack.Pop(); if (stack.Count == 0){ max = i + 1; } else{ max = Math.Max(max, i - stack.Peek()); } } else { stack.Push(i); } } return max; }}
1 0
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses
- LeetCode-Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- LeetCode:Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses
- Leetcode:Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- 递归算法
- 开源项目地址集合
- qt用http协议访问webservice,用crypto的sha256签名
- Android学习—自定义组件
- C++中的空类,默认产生哪些类成员函数?
- LeetCode -- Longest Valid Parentheses
- HDMIkey 格式转换
- iOS8.0 之后UIAlertView和UIActionSheet的创建方式的新变化
- 1.v4l2 framework框架
- Android bluedroid模块间关系
- 苹果6s正式销售,国内多渠道可购买
- android sdk 打包混淆
- LeetCode -- Permutations
- linux 部署项目