Longest Valid Parentheses
问题简介:给定一个只包含字符 ‘(’ 和 ‘)’ 的字符串,找到最长的有效括号子字符串的长度
举例:
1:
输入: “(()”
输出: 2
解释: 最长有效子字符串是 “()”
2:
输入: “)()())”
输出: 4
解释: 最长有效子字符串是"()()"
解法一:
暴力遍历:遍历字符串从i=0开始,count代表有效子字符串长度,截取子字符串,通过一个子方法isValid()判断是否是有效子字符串,这个方法思路是对的,但是当字符串足够长时会超时
class Solution {
private HashMap<Character, Character> mappings;
public Solution(){
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
}
public int longestValidParentheses(String s) {
int length = s.length();
if(length <= 1)return 0;
int count = 0;
for(int i = 0;i<length - 1;i++){
for(int j = i + count;j<length ;j++){
String change = s.substring(i,j+1);
boolean judge = isValid(change);
if(judge == true && (j-i) > count)count=(j-i+1);
}
}
return count;
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (this.mappings.containsKey(c)) {
char topElement = stack.empty() ? '#' : stack.pop();
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}
复杂度分析:
时间复杂度:o(n3)截取字符串需要o(n2),检查一遍需要o(n)
空间复杂度:o(n)最长的子字符串就是o(n)
解法二:
在这种方法中,我们使用两个计数器left和right,首先,我们开始遍历从左到右的字符串,对于每个子字符串遇到’(’,我们增加left计数器和每个’)'我们增加right计数器,每当left等于right时,我们计算当前有效子字符串的长度并跟踪到目前为止找到的最大长度子字符串,如果right变得比left更大,我们将left和right重置为0.然后再从右向左遍历一遍
public class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * right);
} else if (right >= left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * left);
} else if (left >= right) {
left = right = 0;
}
}
return maxlength;
}
}
复杂度分析:
时间复杂度:o(n)
空间复杂度:o(1)
小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海