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.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
解法:很简单,用stack直接秒了。但是要注意下st为空的情况,判断要加好,还有map的使用,还是要多记记基础元素的API~
class Solution {
public boolean isValid(String s) {
if(s.isEmpty()){
return true;
}
int len = s.length();
if(len ==1){
return false;
}
Map<Character,Integer> cnt = new HashMap<Character,Integer>();
cnt.put('(',1); //map是set!
cnt.put(')',-1);
cnt.put('[',2);
cnt.put(']',-2);
cnt.put('{',3);
cnt.put('}',-3);
Stack<Character> st = new Stack<Character>();
char[] is = s.toCharArray();
st.push(is[0]);
for(int i =1; i<len; i++){
if(!st.isEmpty() && cnt.get(is[i])+cnt.get(st.peek()) == 0){ //peek要判断非空
//证明是相等
st.pop();
}else{
st.push(is[i]);
}
}
if(st.isEmpty()){
return true;
}else{
return false;
}
}
}