去哪——尋找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.*;
//1.大寫轉小寫
//2.統計每個coder的個數,出現coder的字符串,用bean存儲並添加到容器中
//3.對容器用Collections.sort排序,首先按出現次數排序,其次按下標排序
//4.由排序規則可以看出,bean中要存放的有下標和出現的個數。
public class Coder {
    public String[] findCoder(String[] strs, int n) {
        // write code here
        if(strs == null||n == 0)
            return strs;
        ArrayList<Bean> array=new ArrayList();
        for(int i=0;i<n;i++)
            {
            String s=strs[i].toLowerCase();//轉成小寫
            if(s.contains("coder"))//是否包含有coder
                {
                int count=0;
                //indexOf()若不存在則返回-1;否則返回首次出現的起始位置.
                int start=0;
                int index=0;
                while(start<s.length()&&(index=s.indexOf("coder",start))!=-1)
                    {
                    count++;
                    start=index+"coder".length();//一頭蠢豬!!!
                }
                array.add(new Bean(strs[i],i,count));
            }   
        }
        //按規則進行排序
        Collections.sort(array,new Comparator<Bean>(){
            public int compare(Bean first,Bean second){
                if(first.count!=second.count)
                    {
                    return second.count-first.count;
                }else
                    {
                    return first.index-second.index;
                }
            }
        });
        String[] result=new String[array.size()];
        for(int i=0;i<result.length;i++)
            {
            result[i]=array.get(i).str;
        }
        return result;
    }
    //Bean 容器
    class Bean{
        String str;
        int index;
        int count;
        public Bean(String str,int index,int count){
            this.str=str;
            this.index=index;
            this.count=count;
        }
    }
}

發佈了205 篇原創文章 · 獲贊 24 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章