最長有效括號(棧)

給定一個只包含 '(' 和 ')' 的字符串,找出最長的包含有效括號的子串的長度。數組

示例 1:網絡

輸入: "(()"
輸出: 2
解釋: 最長有效括號子串爲 "()"

code

示例 2:leetcode

輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串爲 "()()"

字符串

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/longest-valid-parentheses
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。

class

//錯誤寫法,這裏貼出來與後面的AC代碼作對比。錯誤的緣由在於「)()())」的解爲2,記數的方式不行
public class Main {

	public static void main(String[] args) {
		String s = ")()())";
//              String s = ")()((())";
		System.out.println(longestValidParentheses(s));
	}
	
    public static int longestValidParentheses(String s) {
    	int ans = 0;
    	int tmp = 0;
    	Stack<String> stack = new Stack<>();
    	if (s.length() != 0) {
    		stack.push(String.valueOf(s.charAt(0)));
    	}
    	for (int i=1; i<s.length(); i++) {
    		if (stack.peek().equals("(")) {
    			if (String.valueOf(s.charAt(i)).equals(")")) {
    				stack.pop();
    				tmp += 2;
    			} else {
    				stack.push(String.valueOf(s.charAt(i)));
    				tmp = 0;
    			}
    		} else {
    			stack.push(String.valueOf(s.charAt(i)));
    			tmp = 0;
    		}
    		if (tmp > ans) {
    			ans = tmp;
    		}
    	}
    	return ans;
    	
    }
    
}
//仍是用棧,只是如今將數組下標存入棧中。
//遇到'('就將下標存如棧中,遇到')'就將棧頂的下標出棧,而後計算距離
public class Main {

	public static void main(String[] args) {
//		String s = ")()())";
		String s = ")()((())";
		System.out.println(longestValidParentheses(s));
	}
	
    public static int longestValidParentheses(String s) {
    	int ans = 0;
    	Stack<Integer> stack = new Stack<Integer>();
    	stack.add(-1);
    	for (int i=0; i<s.length(); i++) {
    		if (s.charAt(i) == '(') {
    			stack.push(i);
    		} else {
    			stack.pop();
    			if (stack.empty()) {
    				stack.add(i);
    			} else {
    				ans = Math.max(ans, i-stack.peek());
    			}
    		}
    	}
    	return ans;
    }
    
}
相關文章
相關標籤/搜索