package ValidParentheses20;
import java.util.HashMap;
import java.util.Stack;
class Solution {
private HashMap<Character,Character> map = new HashMap<>();
public Solution(){
this.map.put(')','(');
this.map.put('}','{');
this.map.put(']','[');
}
public boolean isValid(String s) {
Stack<Character> stack1 = new Stack<>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (this.map.containsKey(c)){
char top = stack1.empty() ? '#' : stack1.pop();
if (top != map.get(c)){
return false;
}
}else {
stack1.push(c);
}
}
return stack1.empty();
}
public static void main(String[] args) {
System.out.println(new Solution().isValid("([])"));
}
}
心得体会:
- 使用一个hashmap存储括号匹配,代替switch语句和if else语句。
- char top = stack1.empty() ? ‘#’ : stack1.pop(); 用“#”代替判断空栈条件,用stack.pop()代替stack.peek();可以少写一条pop语句。
- 别忘了写else