給定一個只包含 '(' 和 ')' 的字符串,找出最長的包含有效括號的子串的長度。
示例 1:
輸入: "(()"
輸出: 2
解釋: 最長有效括號子串爲 "()"
示例 2:
輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串爲 "()()"
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-valid-parentheses
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
//錯誤寫法,這裏貼出來與後面的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;
}
}