题意:只包含 '(' ')' 寻找最长有效的括号,格式正确且连续如:
符合题意的
(()——2 )()())——4 ()(()——2 ()()()(()——6 ()(())——6
我一开始想用hashmap 加栈做 但是不全
class Solution {
public int longestValidParentheses(String s) {
//能够连续匹配 ()((())) 也符合
if(s==null||s.length()==1) return 0;
Map<Character,Character> hash=new HashMap<>();
hash.put(')','(');
Stack stack=new Stack();
int count=0;
int len=s.length();
int max_len=0;
for(int i=0;i<len;i++){
if(hash.containsKey(s.charAt(i))){//包含右括号
//栈不为空 且 有左括号和右括号匹配
if(!stack.empty() && stack.peek()==hash.get(s.charAt(i)) ){
count+=2;
stack.pop();
}else{
max_len=Math.max(max_len,count);//r如果右括号 匹配终端
count=0;
}
}else{//左括号
//栈为空时入栈 否则不入栈
/*if(stack.empty()){
stack.push(s.charAt(i));
}else{
//max_len=Math.max(max_len,count);//6
//count=0;
continue;
}*/
stack.push(s.charAt(i));
}
}
return max_len>count?max_len:count;
}
}
官方给的解答:
class Solution {
public int longestValidParentheses(String s) {
int maxans = 0;
Deque<Integer> stack = new LinkedList<Integer>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
maxans = Math.max(maxans, i - stack.peek());
}
}
}
return maxans;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官方的规律是 连续且有效,即找到未匹配的右括号的额位置 与最远且匹配了的位置的距离即可。