zoukankan      html  css  js  c++  java
  • Java [leetcode 32]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. 当前栈内无元素,则用start变量记录当前右括号的位置,表明下次比较从该右括号下一个位置开始判断;

    2. 当前栈内有元素,则将栈顶元素弹出。如果弹出后的栈为空,则表明当前括号匹配,这时计算出当前的最长序列长度,即当前位置的值减去start的值即是;

    3. 当前栈内又元素且弹出后的栈内仍然有元素,则最长序列长度为当前元素位置减去栈顶元素的位置。

    本算法仅需要扫描一遍字符串,所以时间复杂度为O(n);

    代码如下:

    public class Solution {
        public int longestValidParentheses(String s) {
    		ArrayList<Integer> location = new ArrayList<Integer>();
    		int len = 0;
    		int start = -1;
    		for (int i = 0; i < s.length(); i++) {
    			if (s.charAt(i) == '(') {
    				location.add(i);
    			} else {
    				if (location.isEmpty()) {
    					start = i;
    				} else {
    					location.remove(location.size() - 1);
    					if (location.isEmpty()) {
    						len = Math.max(len, i - start);
    					} else {
    						int index = location.get(location.size() - 1);
    						len = Math.max(len, i - index);
    					}
    				}
    			}
    		}
    		return len;
    	}
    }
    
  • 相关阅读:
    English trip V1
    English trip V1
    第一类斯特林数
    bzoj 3601 一个人的数论
    bzoj 4407 于神之怒加强版
    bzoj 2693 jzptab
    bzoj 4184 shallot
    luogu P3920 [WC2014]紫荆花之恋
    bzoj 4269 再见Xor
    luogu P2183 [国家集训队]礼物
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4934485.html
Copyright © 2011-2022 走看看