Problem:
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.
Explanation:
判断字符串是否关闭(左右括号配对)。
My Thinking:
使用栈存放开启的括号,一旦出现关闭的括号,则判断它是否与栈顶匹配,不匹配则立即返回false。
My Solution:
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(!stack.isEmpty() && map.containsKey(c) && map.get(c)!=stack.peek()){
return false;
}else if(!map.containsKey(c) || (stack.isEmpty() && map.containsKey(c))){//如果是开启符号或只有一个关闭符号
stack.push(c);
}else{//配对成功
stack.pop();
}
}
return stack.isEmpty();//防止只有一个符号
}
}
Optimum Thinking:
Optimum Solution: