题干描述
每个字符串至少含有一个数字字符,按如下规则降序排序:
(1) 按照字符串中字母字符个数和数字字符个数(字母数字比)的比值大小进行排序。
(2) 若两个字符串的字母数字比相同。则按照字符串本身大小进行排序。
输入值:[“abc123”,“abc+1234”,“abcabab–1”]
返回值:[“abcabab–1”,“abc123”,“abc+1234”]
解题思路
输入是字符串数组,将其转为ArrayList集合,然后调用Collections的sort方法,传入自定义的比较器进行排序。
public class SpecifySort1 {
public String[] specify_sort(String[] words){
ArrayList<String> list = new ArrayList<>();
for(int i = 0;i < words.length;i++){
list.add(words[i]);
}
Collections.sort(list, (x, y) ->{
double a = count(x);
double b = count(y);
if(a == b){
return y.compareTo(x);
}
if(a > b){
return -1;
}
return 1;
});
String[] res = new String[list.size()];
for(int i=0;i<res.length;i++){
res[i] = list.get(i);
}
return res;
}
//测试
public static void main(String[] args) {
String[] words = new String[3];
words[0] = "abc123";
words[1] = "abc+1234";
words[2] = "ababab--1//";
SpecifySort1 specifySort = new SpecifySort1();
String[] res = specifySort.specify_sort(words);
for(String str : res){
System.out.println(str);
}
}
//求字母数字比
private double count(String str){
char[] chars = str.toCharArray();
int alpha = 0;
int digit = 0;
for(char ch : chars){
if(isAlpha(ch)){
alpha++;
}else if(isDigit(ch)){
digit++;
}
}
return 1.0*alpha/digit;
}
private boolean isAlpha(char ch){
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
private boolean isDigit(char ch){
return (ch >= '0' && ch <= '9');
}
}
参考资料:字符串排序