昨晚,一起准备找工作的同学在研究一道算法题,这位大牛,已经拿了华为的offer还这么拼,叫我们这些投了简历杳无回音的人 额,闲话不多说了,原题要求如下:
case 1: 忽略大小写排序, 如:"Type", 排序后 “epTy”
case 2: 同样的字符不分大小写需要有序,如:"tTypet "; 排序后为:"eptTty"
case 3:若为其他字符 则乖乖待在原地别动, 如:"tp?ye"; 排序后为: "ep?ty"
给出一个完善的case: "A Famous Saying: Much Ado About Nothing(2012/8)." 排序后:"A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8)."
各位看官,就是这么简单, 小弟不才,只想到如下处理方案, 略复杂。
思路:先排除特殊字符,先将 A~Z, 和a~z的相对顺序排好,以"tTy?pet "为例:
1. 把特殊字符甩开,先将字符的相对顺序进行排序。实际操作:申请一个动态二维数组,横坐标维是对应的256个ASCLL长,实际上只用了a~z这26个,纵坐标维就是对应的字符数组, 当为非特殊字符时,先获取到该字符的ASCLL码,再在对应的行上进行追加,如果是大写的字符 如'T',就将其ASCLL码加上32映射到对应的小写字符维上面来
2. 再将对应的特殊字符插入到对应的位置即可。
上代码:
</pre><p><pre name="code" class="java">import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static void main(String []args) {
String s = "A Famous Saying: Much Ado About Nothing(2012/8).";
//A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).
if(s == null || s.length() == 0) return;
char []chs = getCharArray(s);
//将特殊字符插入到排序后的数组中
char [] res = new char[s.length()];
int len = s.length();
int j = chs.length - 1;
for(int i = len - 1; i >= 0; i--) {
char ch = s.charAt(i);
if(!(ch >= 'A' && ch <= 'Z') && !(ch >= 'a' && ch <= 'z')) {
res[i] = ch;
} else {
res[i] = chs[j--];
}
}
//输出
for(int i = 0; i < len; i++)
System.out.print(res[i]);
}
private static char[] getCharArray(String s) {
//申请二维动态数组
List<List<Character>> list = new ArrayList<List<Character>>(256);
int [] arr = new int[26];
for(int i = 0; i < 256; i++) {
ArrayList<Character> al = new ArrayList<>();
list.add(al);
}
//将非特殊字符存入偶们的动态数组中
int len = s.length();
int cnt = 0;
for(int i = 0; i < len; i++) {
char ch = s.charAt(i);
if((ch >= 'A' && ch <= 'Z')) {
list.get(ch + 32).add(ch);
cnt++;
} else if((ch >= 'a' && ch <= 'z')) {
list.get(ch).add(ch);
cnt++;
}
}
//将排序后的结果存入一个字符数组并返回,该数组中仅存放 A~Z 和a~z
char []chs = new char[cnt];
int index = 0;
for(int i = 0; i < 256; i++) {
List<Character> ll = list.get(i);
if(ll.size() > 0) {
for(Character ch: ll) {
chs[index++] = ch;
}
}
}
return chs;
}
}