zoukankan      html  css  js  c++  java
  • LeetCode 32 括号匹配

    [LeetCode 32] Longest Valid Parentheses

    题目

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
    

    测试案例

    Input: "(()"
    Output: 2
    Explanation: The longest valid parentheses substring is "()"
    
    Input: ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()"
    

    思路

    1. 采用栈数据结构。栈中存放各字符的下标。初始时里面放入-1。

    2. 从左至右依次遍历每个字符。当前字符为左括号就进栈。当前字符为右括号时,如果栈中存在左括号,则出栈。否则,入栈。

    3. 每当都元素,记下标为 i ,进栈时,就用 i - stack.peek() - 1 更新 max。

    4. 遍历结束后,需要用 n - stack.peek() - 1 更新 max。

    代码如下

    class Solution {
        public int longestValidParentheses(String s) {        
            int max = 0, n = s.length(), temp, index = 0; 
            if(n == 0){
                return 0;
            }
            int[] stack = new int[n + 1];        
            stack[index++] = -1;
            for(int i = 0; i < n; i++){
                if(s.charAt(i) == '(' || (temp = stack[index - 1]) == -1 || 
                   s.charAt(temp) == ')'){                               
                    if((temp = i - stack[index - 1] - 1) > max){
                        max = temp;
                    }                
                    stack[index++] = i;
                }
                else{
                    index--;                
                }            
            }
            if((temp = n - stack[index - 1] - 1) > max){
                max = temp;
            }        
            return max;
        }
    }
    
  • 相关阅读:
    bzoj 3262: 陌上花开
    hdu 5618 Jam's problem again
    bzoj 1176: [Balkan2007]Mokia
    bzoj 2683: 简单题
    Codevs 1080 线段树练习(CDQ分治)
    bzoj 3223: Tyvj 1729 文艺平衡树
    bzoj 1503: [NOI2004]郁闷的出纳员
    bzoj 1208: [HNOI2004]宠物收养所
    bzoj 1588: [HNOI2002]营业额统计
    bzoj 3224: Tyvj 1728 普通平衡树
  • 原文地址:https://www.cnblogs.com/echie/p/9589097.html
Copyright © 2011-2022 走看看