zoukankan      html  css  js  c++  java
  • LeetCode--032--最长有效括号(java)

    给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

    示例 1:

    输入: "(()"
    输出: 2
    解释: 最长有效括号子串为 "()"
    

    示例 2:

    输入: ")()())"
    输出: 4
    解释: 最长有效括号子串为 "()()"

    start纪录第一个有效括号的位置,当遇到右括号时,看和其匹配的左括号的位置在哪,得到该有效括号的长度。

     1 class Solution {
     2     public int longestValidParentheses(String s) {
     3         Stack<Integer> stack = new Stack();
     4         int start = -1;//当情况为(()) 3 + 1 = 4
     5         int res = 0;
     6         for(int i = 0;i < s.length();i++){
     7             if(s.charAt(i) == '('){
     8                 stack.push(i);
     9             }else{
    10                 if(stack.isEmpty()){
    11                     start = i;
    12                 }else{
    13                     stack.pop();
    14                     if(stack.isEmpty()){
    15                         res = Math.max(res,i-start);
    16                     }else{
    17                         res = Math.max(res,i - stack.peek());
    18                     }
    19                 }
    20             }
    21         }
    22         return res;
    23     }
    24 }

    2019-04-25 18:39:32

  • 相关阅读:
    GeoHash核心原理解析
    线程安全与可重入函数
    malloc和free的实现
    数字金字塔最大路径和——递归
    TCP连接建立与断开
    Gray Code
    C压缩字符串中的空格
    C++链接与装载
    epoll测试实例
    C++之手写strlen函数
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10770279.html
Copyright © 2011-2022 走看看