/**
- 阿里面试题
- Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
- 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.
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class Main1 {
private final Map<Character,Character> map = new HashMap<>();
Main1(){
map.put(')','(');
map.put(']','[');
map.put('}','{');
}
public boolean check(String str){
Stack<Character> stack = new Stack<>();
for(Character c:str.toCharArray()){
if(map.containsValue(c)){
stack.push(c);
continue;
}
if(map.containsKey(c)){
if(stack.empty()) {
return false;
}
Character character = stack.pop();
if(!map.get(c).equals(character)) {
return false;
}
}
}
return stack.empty();
}
public static void main(String[] args) {
Main1 main1 = new Main1();
Boolean flag = main1.check("{");
System.out.println(flag);
Boolean flag2 = main1.check("}");
System.out.println(flag2);
Boolean flag3 = main1.check("{]}");
System.out.println(flag3);
Boolean flag4 = main1.check("{[}");
System.out.println(flag4);
Boolean flag5 = main1.check("{[]}");
System.out.println(flag5);
}
}
输出结果: