zoukankan      html  css  js  c++  java
  • LongestValidParentheses, 求最长合法括号子串长度-----同类问题ValidParentheses,GenerateParentheses

    问题描述:求括号字符串中最长合法子串长度。例如:()((),返回2,而不是4.

    算法分析:还是利用栈,和判断合法括号对是一样的。

     1 public static int longestValidParentheses(String s) {
     2         Stack<int[]> stack = new Stack<int[]>();
     3         int result = 0;
     4      
     5         for(int i=0; i<=s.length()-1; i++)
     6         {
     7             char c = s.charAt(i);
     8             if(c=='(')//如果是左括号
     9             {
    10                 int[] a = {i,0};
    11                 stack.push(a);
    12             }
    13             else//如果是右括号
    14             {
    15                 if(stack.empty()||stack.peek()[1]==1)//如果栈为空或者栈顶元素为右括号
    16                 {
    17                     int[] a = {i,1};
    18                     stack.push(a);
    19                 }
    20                 else
    21                 {
    22                     stack.pop();
    23                     int currentLen=0;
    24                     if(stack.empty())
    25                     {
    26                         currentLen = i+1;
    27                     }
    28                     else
    29                     {
    30                         currentLen = i-stack.peek()[0];
    31                     }
    32                     result = Math.max(result, currentLen);
    33                 }
    34             }
    35         }
    36      
    37         return result;
    38     }
  • 相关阅读:
    线程安全
    Kafka分区原理图
    Zookeeper02
    Zookeeper01
    kafka01
    20170623_oracle_SQL
    20170623_oracle备份和恢复_常见问题
    20170623_oracle基础知识_常见问题
    数字类型入门
    数据类型基础
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5571223.html
Copyright © 2011-2022 走看看