题目描述
请设计一个高效算法,再给定的字符串数组中,找到包含"Coder"的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照"Coder"出现的次数递减排列,若两个串中"Coder"出现的次数相同,则保持他们在原数组中的位置关系。
给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。
测试样例:
["i am a coder","Coder Coder","Code"],3
返回:["Coder Coder","i am a coder"]
题目链接
答案解析1
import java.util.*;
public class Coder {
public String[] findCoder(String[] A, int n) {
// write code here
String[] s=new String[301];
int num=0;
int len=0;
for(int i=0;i<n;i++){
String a=(" "+A[i]+" ").toLowerCase();
String[] str=a.split("coder");
num=str.length-1;
if(num!=0){
s[len++]=A[i]+","+i+","+num;
}
num=0;
}
return bubbleSort(s,len);
}
public static String[] bubbleSort(String[] array,int n) {
String[] arr=new String[n];
String temp = "";
int len=0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
int a=Integer.parseInt(array[j].split(",")[2]);
int b=Integer.parseInt(array[j+1].split(",")[2]);
if (a > b) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
if(a==b){
int aa=Integer.parseInt(array[j].split(",")[1]);
int bb=Integer.parseInt(array[j+1].split(",")[1]);
if(aa<bb){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
for(int i=n-1;i>=0;i--){
arr[len++]=array[i].split(",")[0];
}
return arr;
}
}
答案解析2
import java.util.*;
public class Coder {
public String[] findCoder(String[] A, int n) {
// write code here
HashMap<String,Integer> hashMap=new HashMap<>();
int num=0;
for(int i=0;i<n;i++){
String a=(" "+A[i]+" ").toLowerCase();
String[] str=a.split("coder");
num=str.length-1;
if(num!=0){
hashMap.put(A[i]+","+i,num);
}
num=0;
}
String[] s=new String[hashMap.size()];
Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
s[num++]=entry.getKey()+","+entry.getValue();
}
return bubbleSort(s);
}
public static String[] bubbleSort(String[] array) {
String temp = "";
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
int a=Integer.parseInt(array[j].split(",")[2]);
int b=Integer.parseInt(array[j+1].split(",")[2]);
if (a > b) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
if(a==b){
int aa=Integer.parseInt(array[j].split(",")[1]);
int bb=Integer.parseInt(array[j+1].split(",")[1]);
if(aa<bb){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
String[] arr=new String[array.length];
int len=0;
for(int i=array.length-1;i>=0;i--){
arr[len++]=array[i].split(",")[0];
}
return arr;
}
}
参考链接
https://blog.csdn.net/qy1387/article/details/7752973(Java常用排序算法/程序员必须掌握的8大排序算法)
https://baike.xsoftlab.net/view/250.html (Java map 详解 - 用法、遍历、排序、常用API等)
http://nkeys.logdown.com/posts/474643-sort-map-by-value-in-java(在java中如何對Map的value進行排序?)