寻找Coder

题目:
请设计一个高效算法,再给定的字符串数组中,找到包含”Coder”的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照”Coder”出现的次数递减排列,若两个串中”Coder”出现的次数相同,则保持他们在原数组中的位置关系。

给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。

测试样例:
[“i am a coder”,”Coder Coder”,”Code”]
3
返回:
[“Coder Coder”,”i am a coder”]

代码:

import java.util.*;

class Recorder{
    private String data; //字符串
    private int index; //在原数组中的位置
    private int count;  //含有多少个coder-1
    public Recorder(String data, int index, int count){
        this.data = data;
        this.index = index;
        this.count = count;
    }
    public String getData(){return data;}
    public int getIndex(){return index;}
    public int getCount(){return count;}
}

public class Coder {
    //统计"coder"出现的次数
    static int count(String a, String b){
        int count=0;
        int fromIndex=0;
        while(fromIndex!=-1){
            fromIndex=a.indexOf(b,fromIndex);
            if(fromIndex!=-1){
                fromIndex+=b.length();
                count++;
            }
        }
        return count;
    }
    public String[] findCoder(String[] A, int n){
        ArrayList<Recorder> result = new ArrayList<Recorder>();
        for(int i=0;i<n;i++){
            String a = A[i].toLowerCase();  //转小写
            if(a.contains("coder")){
                int count = 0;                      
                //遍历a查找"coder"
                count = count(a, "coder");
                result.add(new Recorder(a, i, count));
            }
        }
        //使用Collections提供的对List的归并排序
        //需实现其Comparator接口参数
        Collections.sort(result, new Comparator<Recorder>() {
            public int compare(Recorder o1, Recorder o2){
                 //先比"coder"个数, count大者排前面
                if(o1.getCount() != o2.getCount())
                    return o2.getCount() - o1.getCount();
                 //再比index, index小者排前面
                else return o1.getIndex() - o2.getIndex();
            }
        });
        String sorted[] = new String[result.size()];
        for(int i=0;i<result.size();i++){
            String s = result.get(i).getData();
            sorted[i] = s;
        }
        return sorted;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值