• 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;
    	}
    }
    
  • 相关阅读:
    申港集中运营平台Linux测试环境架构搭建
    收获,不止oracle
    Oracle函数
    Apache+php安装和配置 windows
    mysql for windows(服务器)上的配置安装--实例
    软件工程实践总结--爬山成长
    Alpha版本十天冲刺——Day 8
    Alpha版本十天冲刺——Day 2
    软件产品案例分析--K米
    第二次结对编程作业——毕设导师智能匹配
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4934485.html
Copyright © 2020-2023  润新知