题目描述
请设计一个高效算法,再给定的字符串数组中,找到包含"Coder"的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照"Coder"出现的次数递减排列,若两个串中"Coder"出现的次数相同,则保持他们在原数组中的位置关系。
给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。
测试样例:
["i am a coder","Coder Coder","Code"],3
返回:["Coder Coder","i am a coder"]
public class BinarySearch {
public static void main(String[] args) {
BinarySearch b=new BinarySearch();
// 测试用例:
// ["coder","dccoderrlcoderxxpicoderhcoderbiwcoderdcoderrcodermcoderdbvcodertrwvycoderimvcoderuswfccoderczecoderczncoderkfuehcoderocoderiuvccoderfwcodervdiycoderifqjcoder","vxroicoderdqcoderfvcodermtyrcoderlcoderwrygcoder","hcoderwzmjccoderamfmvcoderazmcoderhcodersnuccoderceocodermsmifcoderpwpcodertqbqcoderentbcoderxsgpkcoderrqrbcoderucoder"],4
// 对应输出应该为:
// ["dccoderrlcoderxxpicoderhcoderbiwcoderdcoderrcodermcoderdbvcodertrwvycoderimvcoderuswfccoderczecoderczncoderkfuehcoderocoderiuvccoderfwcodervdiycoderifqjcoder","hcoderwzmjccoderamfmvcoderazmcoderhcodersnuccoderceocodermsmifcoderpwpcodertqbqcoderentbcoderxsgpkcoderrqrbcoderucoder","vxroicoderdqcoderfvcodermtyrcoderlcoderwrygcoder","coder"]
int num=4;
String[] strA={"coder","codercodercoder","codercodercoder55","codercodercoder66"};
// String[] strA={"coder","codercodercoder","dccoderrlcoderxxpicoderhcoderbiwcoderdcoderrcodermcoderdbvcodertrwvycoderimvcoderuswfccoderczecoderczncoderkfuehcoderocoderiuvccoderfwcodervdiycoderifqjcoder","vxroicoderdqcoderfvcodermtyrcoderlcoderwrygcoder","hcoderwzmjccoderamfmvcoderazmcoderhcodersnuccoderceocodermsmifcoderpwpcodertqbqcoderentbcoderxsgpkcoderrqrbcoderucoder"};
// String[] strA={"dccoderrlcoderxxpicoderhcoderbiwcoderdcoderrcodermcoderdbvcodertrwvycoderimvcoderuswfccoderczecoderczncoderkfuehcoderocoderiuvccoderfwcodervdiycoderifqjcoder","hcoderwzmjccoderamfmvcoderazmcoderhcodersnuccoderceocodermsmifcoderpwpcodertqbqcoderentbcoderxsgpkcoderrqrbcoderucoder","vxroicoderdqcoderfvcodermtyrcoderlcoderwrygcoder","coder"};
String[] strB=b.findCoder(strA, num);
for(int i=0;i<strB.length;i++){
System.out.println(strB[i]);
}
}
public String[] findCoder(String[] A, int n) {
String[] BB=new String[n];
int k;
int m=0;
for(k=0;k<n;k++){
if(A[k].contains("coder") || A[k].contains("Coder") ){
int count=0;
int step=0;
while(step<A[k].length()-4){
if(A[k].substring(step, step+5).equalsIgnoreCase("coder")){
count++;
step=step+5;
}else{
step++;
}
}
BB[m]=A[k]+" "+count;//将包含coder的字符串放入BB字符串数组中;
m++;
}//end if
}//end for
//将非空字符串排序,排序方法是选择排序
String tmp=null;
String[] strB=new String[m];
for(int i=0;i<m;i++){//需要稳定排序
for(int j=m-1;j>i;j--){
String[] bb=BB[j].split(" ");
String[] cc=BB[j-1].split(" ");
int t=Integer.parseInt(bb[bb.length-1]);
int t1=Integer.parseInt(cc[cc.length-1]);
if(t>t1){
tmp=BB[j];
BB[j]=BB[j-1];
BB[j-1]=tmp;
}
}
}
for(int i=0,yy=0;i<m;i++,yy++){
String[] dd=BB[i].split(" ");
int countactLong=dd[dd.length-1].length()+1;
strB[yy]=BB[i].substring(0,BB[i].length()-countactLong);
}
return strB;
}
}