阿里面试题之符号匹配

/**

  • 阿里面试题
  • Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    1. Open brackets must be closed by the same type of brackets.
    1. 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 map = new HashMap<>();

    Main1(){
        map.put(')','(');
        map.put(']','[');
        map.put('}','{');
    }

    public boolean check(String str){
        Stack 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);
    }
}

输出结果:


1588215309(1).jpg

你可能感兴趣的:(阿里面试题之符号匹配)