给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
class Solution {
public boolean isValid(String s) {
Map<Character,Character> map = new HashMap<>();
map.put('(',')');
map.put('[',']');
map.put('{','}');
Stack<Character> stack = new Stack<>();
for(int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if(map.get(c)!=null) {
stack.push(c);
continue;
}
if(stack.empty()) {
return false;
}
Character top = stack.pop();
if(map.get(top).equals(c)) {
continue;
}
return false;
}
if(stack.empty()) {
return true;
}
return false;
}
}
有效降低下边代码的圈复杂度
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if(c=='('||c=='['||c=='{') {
stack.push(c);
continue;
}
if(stack.empty()) {
return false;
}
Character top = stack.pop();
if(top=='(' && c==')') {
continue;
}
if(top=='[' && c==']') {
continue;
}
if(top=='{' && c=='}') {
continue;
}
return false;
}
if(stack.empty()) {
return true;
}
return false;
}
}