给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
public boolean isValid(String s) {
while (s.contains("()") || s.contains("[]") || s.contains("{}")) {
s = s.replace("()", "");
s = s.replace("[]", "");
s = s.replace("{}", "");
}
return s.isEmpty();
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
int length = s.length();
for (int i = 0; i < length; i++) {
if (s.charAt(i) == ‘(‘ || s.charAt(i) == ‘[‘ || s.charAt(i) == ‘{‘) {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty()) return false;
char temp = stack.pop();
if (temp == ‘(‘ && s.charAt(i) != ‘)‘) return false;
if (temp == ‘[‘ && s.charAt(i) != ‘]‘) return false;
if (temp == ‘{‘ && s.charAt(i) != ‘}‘) return false;
}
}
return stack.isEmpty();
}
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(‘(‘, ‘)‘);
map.put(‘[‘, ‘]‘);
map.put(‘{‘, ‘}‘);
Stack<Character> stack = new Stack<>();
int length = s.length();
for (int i = 0; i < length; i++) {
if (map.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty()) return false;
char temp = stack.pop();
if (map.get(temp) != s.charAt(i)) return false;
}
}
return stack.isEmpty();
}
原文:https://www.cnblogs.com/init-qiancheng/p/14732904.html