请设计一个高效算法,再给定的字符串数组中,找到包含”Coder”的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照”Coder”出现的次数递减排列,若两个串中”Coder”出现的次数相同,则保持他们在原数组中的位置关系。 给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。 测试样例: [“i am a coder”,”Coder Coder”,”Code”],3 返回:[“Coder Coder”,”i am a coder”]
package 寻找Coder;
import java.util.Arrays;
class Recorder implements Comparable<Recorder>{
private String str;
private int cnt;
public Recorder(String str, int cnt) {
super();
this.str = str;
this.cnt = cnt;
}
public String getStr() {
return str;
}
public int getCnt() {
return cnt;
}
@Override
public int compareTo(Recorder o) {
// TODO Auto-generated method stub
if ( this.cnt != o.cnt){
return o.cnt - this.cnt;
}
return 0;
}
}
public class Coder{
public String[] findCoder(String[] A, int n) {
// write code here
Recorder[] recorders = new Recorder[n];
String str = "coder";
for ( int i = 0 ; i < n ; i++){
String tmp = A[i].toLowerCase();
int cnt = 0;
for ( int j = 0 ; j < tmp.length() ; j++){
if (tmp.substring(j, j+5).equals(str)){
cnt++;
j += 5;
continue;
}
}
recorders[i] = new Recorder(A[i], cnt);
}
Arrays.sort(recorders);
String[] coder = new String[n];
for ( int i = 0 ; i < n ; i++){
coder[i] = recorders[i].getStr();
}
return coder;
}
}