题目:
题目:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例:
示例:
输入: "([)]"
输出: false
代码:
public class Test12 {
@Test
public void test(){
String test = "([)";
System.out.println(new Test12().isValid(test));
}
public boolean isValid(String s) {
Map<Character,Character> map = new HashMap<Character,Character>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
Stack<Character> stack = new Stack<Character>();
char[] test = s.toCharArray();
for (char c : test) {
if (stack.empty()) {
stack.push(c);
}else{
if( map.get(stack.peek())==null){
break;
}else if (map.get(stack.peek()).equals(c)) {
stack.pop();
}else{
stack.push(c);
}
}
}
return stack.isEmpty();
}
}