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

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

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

java代码:

public class Main5 {

    static boolean isMatch(String s) {
        Stack<Character> sk = new Stack<Character>();
        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<Character> 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<Character> list = new ArrayList<Character>();
        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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • 【生来堙灭星海,死后化作尘埃。】 后来 一些跌撞的时光 酿成了十八年的女儿红 你醉在酒里 无人唤醒 黄昏赠与你的千...
    亦弋阅读 195评论 0 0
  • #幸福是需要修出来的~每天进步1%~幸福实修13班~08李玉珍# 20171128(1/60) 【幸福三朵玫瑰】 ...
    stx2010阅读 145评论 3 0
  • 目录 黎浩对我述说往事的那天,本应是他与乔生庆祝他们在一起百天纪念的日子。我们在一家小餐馆里相对而坐,桌上摆满了酒...
    dd仔阅读 1,108评论 5 4