2021届秋招--爱奇艺笔试--匹配括号

题目描述:输入字符串只包括{}[](),检查是否正确匹配

思路:简单题,栈顶匹配就完事了

public class Num3 {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String inString = in.next();
        LinkedList charStack = new LinkedList<>();
        boolean res = true;
        char smallLeft = '(';
        char smallRight = ')';
        char middleLeft = '[';
        char middleRight = ']';
        char bigLeft = '{';
        char bigRight = '}';
        HashMap kuoMap = new HashMap<>();
        kuoMap.put(smallRight,smallLeft);
        kuoMap.put(middleRight,middleLeft);
        kuoMap.put(bigRight,bigLeft);
        for (int i = 0; i < inString.length(); ++i){
            char inStringIndex = inString.charAt(i);
            if (kuoMap.containsKey(inStringIndex)){
                if (charStack.size() == 0){
                    res = false;
                    break;
                }
                if (kuoMap.get(inStringIndex) == charStack.getLast()){
                    charStack.removeLast();
                }else {
                    res = false;
                    break;
                }
            }else {
                charStack.add(inStringIndex);
            }
        }
        if (charStack.size() > 0)
            res = false;
        if (res)
            System.out.println("True");
        else
            System.out.println("False");
    }
}

注意:我的思路是把括号放入map,key是右括号,val是左括号。检查当前是否为右括号,如果不是就add;如果是就检查栈顶和当前key的val是否一致。这里要注意list可能为空,要先判断是否为空。

你可能感兴趣的:(Java,java,算法)