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;
    	}
    }
    
  • 相关阅读:
    通过USB转TTL串口下载stm32程序
    实验一:基于STM32F1的流水灯实验(库函数)
    opencv 常用头文件介绍
    OpenCV 1.0在VC6下安装与配置(附测试程序)
    在Angularjs使用中遇到的那些坑
    js和ts关于遍历的几个小总结
    angularjs的启动方式
    关于跨域和如何解决跨域问题的小结
    TypeScript(入门)
    截取字符串部分汇总
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4934485.html
Copyright © 2011-2022 走看看