去哪儿 寻找Coder

来源:互联网 发布:河南网络电视 编辑:程序博客网 时间:2024/04/28 14:56

题目描述

请设计一个高效算法,再给定的字符串数组中,找到包含”Coder”的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照”Coder”出现的次数递减排列,若两个串中”Coder”出现的次数相同,则保持他们在原数组中的位置关系。
给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。
测试样例:
[“i am a coder”,”Coder Coder”,”Code”],3
返回:[“Coder Coder”,”i am a coder”]

static class Element {        String str;        int count;    }    public String[] findCoder(String[] A, int n) {        ArrayList<Element> arr = new ArrayList<>();        for (int i = 0; i < n; i++) {            int count = getCount(A[i]);            if (count > 0) {                Element el = new Element();                el.str = A[i];                el.count = count;                arr.add(el);            }        }        Collections.sort(arr, new Comparator<Element>() {            @Override            public int compare(Element e1, Element e2) {                return e2.count - e1.count;            }        });        String[] res = new String[arr.size()];        for (int i = 0,size = arr.size(); i < size; i++) {            res[i] = arr.get(i).str;        }        return res;    }    private static int getCount(String str) {        int count = 0;        str = str.toLowerCase();        String s = "coder";        int index = 0;        while ((index = str.indexOf(s,index)) != -1) {            index += s.length();            ++count;        }        return count;    }
0 0
原创粉丝点击