京东笔试题——括号匹配问题

昨天朋友笔试,大家做着玩的题

首先,会给我们一个已经括号匹配的串,然后成对去掉,问有多少种情况,具体可以看一下下图。

京东笔试题——括号匹配问题_第1张图片
京东笔试题——括号匹配问题_第2张图片

java代码:

public class Main5 {

    static boolean isMatch(String s) {
        Stack sk = new Stack();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                sk.push('(');
            }
            if (s.charAt(i) == ')') {
                if (!sk.isEmpty() && sk.pop() == '(')
                    continue;
                else
                    return false;
            }
        }
        if (sk.isEmpty())
            return true;
        else
            return false;
    }

    public static String ArrayListToString(ArrayList list) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result += list.get(i);
        }
        return result;
    }

    public static int Dong2(String text) {
        int result = 1;
        int count = 0;
        int charsCount = text.length();
        char[] chars = text.toCharArray();
        int where = 0;

        ArrayList list = new ArrayList();
        for (int i = 0; i < charsCount; i++) {
            list.add(chars[i]);
        }
        while (list.contains('(')) {
            list.remove(0);
            for (int j = 0; j < list.size(); j++) {
                Character character = list.remove(j);
                if (isMatch(ArrayListToString(list))) {
                    count++;
                    where = j;
                }
                list.add(j, character);
            }
            list.remove(where);
            result = result * count;
            count = 0;
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(Dong2("(((())))"));
        System.out.println(Dong2("((()))"));
        System.out.println(Dong2("(())"));
        System.out.println(Dong2("()()()"));

    }

}

输出:

24
6
2
1

你可能感兴趣的:(京东笔试题——括号匹配问题)