请设计一个高效算法,再给定的字符串数组中,找到包含”Coder”的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照”Coder”出现的次数递减排列,若两个串中”Coder”出现的次数相同,则保持他们在原数组中的位置关系。
给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Coder {
public class Node{
private String s;
private Integer cnt;
public Node(String s, Integer cnt) {
super();
this.s = s;
this.cnt = cnt;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public Integer getCnt() {
return cnt;
}
public void setCnt(Integer cnt) {
this.cnt = cnt;
}
@Override
public String toString() {
return "Node [s=" + s + ", cnt=" + cnt + "]";
}
}
public Integer match(String s){
Pattern pattern=Pattern.compile("coder",Pattern.CASE_INSENSITIVE);
Matcher matcher=pattern.matcher(s);
Integer count=0;
while(matcher.find()){
count++;
}
return count;
}
public String[] findCoder(String[] A, int n) {
// write code here
List<Node> list=new ArrayList<Node>();
for(int i=0;i<A.length;i++){
Integer count=match(A[i]);
if(count<=0) continue;
list.add(new Node(A[i],count));
}
Collections.sort(list,new Comparator<Node>(){
@Override
public int compare(Node o1, Node o2) {
if(o1.getCnt()==o2.getCnt()) return 0;
else return o1.getCnt()<o2.getCnt() ? 1:-1;
}
});
List<String> ans=new ArrayList<String>();
for(Node node:list){
ans.add(node.getS());
}
return ans.toArray(new String[list.size()]);
}
}