题目
题解
按照字符依次判断,ASCII小的在前面,当前字符相等则判断下一个字符,这也是String源码compareTo方法排序算法。
public Comparator<String> stringComparator() {
return (s1, s2) -> {
int len1 = s1.length();
int len2 = s2.length();
int minLength = len1 > len2 ? len2 : len1;
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int index = 0;
while (index < minLength) {
char char1 = c1[index];
char char2 = c2[index];
if (char1 != char2) {
return char1 - char2;
}
index++;
}
return len1 - len2;
};
}
时间负责度:O(n)