当前位置: 首页 > news >正文

LeetCode -- 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.






思路:
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;
    }
}




	


相关文章:

  • 利用Intel博锐技术解决桌面管理难题
  • LeetCode -- Permutations
  • LeetCode -- Construct Binary Tree from Inorder and Postorder Traversal
  • 王小云:十年破译五部顶级密码
  • LeetCode -- Factorial Trailing Zeroes
  • LeetCode -- Gas Station
  • 山东大学王小云教授成功破解MD5
  • LeetCode -- Implement Trie (Prefix Tree)
  • 2009年的3G上网卡市场,华为将会领跑
  • LeetCode -- Kth Smallest Element in a BST
  • SQL2005CLR函数扩展-环比计算
  • LeetCode -- Majority Element
  • LeetCode -- Max Points on a Line
  • ArcGIS Server Java ADF 案例教程 17
  • LeetCode -- Maximal Square
  • 【翻译】babel对TC39装饰器草案的实现
  • Codepen 每日精选(2018-3-25)
  • JavaScript中的对象个人分享
  • JAVA多线程机制解析-volatilesynchronized
  • JS数组方法汇总
  • markdown编辑器简评
  • PAT A1050
  • php ci框架整合银盛支付
  • Python 基础起步 (十) 什么叫函数?
  • 安卓应用性能调试和优化经验分享
  • 技术发展面试
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 跨域
  • 浏览器缓存机制分析
  • 每天一个设计模式之命令模式
  • 配置 PM2 实现代码自动发布
  • 使用Swoole加速Laravel(正式环境中)
  • 吐槽Javascript系列二:数组中的splice和slice方法
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • 自定义函数
  • 06-01 点餐小程序前台界面搭建
  • 教程:使用iPhone相机和openCV来完成3D重建(第一部分) ...
  • ​水经微图Web1.5.0版即将上线
  • #pragma 指令
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (Matalb回归预测)PSO-BP粒子群算法优化BP神经网络的多维回归预测
  • (待修改)PyG安装步骤
  • (翻译)Quartz官方教程——第一课:Quartz入门
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (新)网络工程师考点串讲与真题详解
  • (一)Thymeleaf用法——Thymeleaf简介
  • (转)LINQ之路
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • .htaccess配置常用技巧
  • .NET Core 和 .NET Framework 中的 MEF2