Problem
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Note
建立堆栈stack。循环每个元素放入堆栈或比较是否和栈顶元素成对。
循环结束后,若未抛出false,且堆栈为空,说明所有parenthese都已一一对应。
Solution
HashMap+Switch/case
public 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++) {
Character ch = s.charAt(i);
switch (ch) {
case '{': case '[': case '(':
stack.push(ch);
break;
case ')': case '}': case ']':
if (stack.isEmpty() || ch != map.get(stack.pop())) return false;
}
}
return stack.isEmpty();
}
}
if-else branches
public class Solution {
/**
* @param s: A string
* @return: whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
char[] str = s.toCharArray();
if (str.length % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (char ch: str) {
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
if (stack.isEmpty()) {
return false;
} else {
char top = stack.pop();
if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
return false;
}
}
}
}
return stack.isEmpty();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。