20. Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, '['and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
最开始的思路是做个通过map来分别储存左右括号,同时使用计数器来统计各个括号的数量,可以解决"({[]})"的情况,但无法针对各个括号的位置,类似“([)]”的情况。进一步思考,我们想到了栈的算法,先进后出
public boolean isValidByStack(String s) {
char[] chars = s.toCharArray();
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap();
map.put(')', '(');
map.put('}', '{');
map.put(']', '[');
for (int i = 0; i < chars.length; i++) {
if (map.containsKey(chars[i])) {
char topElement = stack.isEmpty() ? '#' : stack.pop();
if (topElement != map.get(chars[i])) {
return false;
}
} else {
stack.push(chars[i]);
}
}
return stack.empty();
}
如果进入的是反括号,则把栈顶的pop出来进行比较,如果不是一对则返回false,如果一致则该对括号都被pop,直到最后整个栈空了,返回true
这里发现题解里有个奇淫技巧的方法,一起来分享下:
public boolean isValid(String s) {
while (s.contains("{}") || s.contains("[]") || s.contains("()")) {
s = s.replace("{}", "");
s = s.replace("[]", "");
s = s.replace("()", "");
}
return "".equals(s);
}
不断的逐对替换括号,最后来判断结果是否为空,虽然效率不高,但是思路不得不让人拍案叫绝!