Level:
Easy
题目描述:
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保存三种括号的对应关系,同时设置一个栈,遍历字符串,如果遇到的是左括号,那么入栈,如果遇到的是右括号,判断栈顶的符号是不是其对应的左括号,如果是则栈顶弹出,如果不是则括号不匹配,遍历完字符串后判断栈是否为空,如果为空则括号匹配,如果不为空,则不匹配。
代码:
class Solution {
public boolean isValid(String s) {
HashMap<Character,Character>map=new HashMap<>();
map.put('(',')');
map.put('[',']');
map.put('{','}');
Stack<Character>stack=new Stack<>();
for(int i=0;i<s.length();i++){
if(stack.isEmpty()){
if(s.charAt(i)==')'||s.charAt(i)==']'||s.charAt(i)=='}')
return false;
else
stack.push(s.charAt(i));
}else{
if(s.charAt(i)==map.get(stack.peek()))
stack.pop();
else if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
stack.push(s.charAt(i));
else
return false;
}
}
if(stack.isEmpty())
return true;
else
return false;
}
}