我必须编写一个函数,该函数需要2个char[]
并返回:
-1
,如果第一个单词按字典顺序排在第二个单词之前0
,如果它们是相同的单词1
(如果之后出现)我知道compareTo()
方法,但这是一个分配,我需要避免使用它。到目前为止,我的代码运行良好,我用不同的词做了一些测试。
我想知道是否还有另一种方式,我的代码没有被优化,它又长又重复:
public static int lexico(char[] word1, char[] word2) {
int length1 = word1.length;
int length2 = word2.length;
if (length1 == length2) {
for (int i = 0; i < length1; i++) {
if (word1[i] < word2[i]) {
return -1;
} else if (word1[i] > word2[i]) {
return 1;
} else if (i == length1 - 1) {
return 0;
}
}
}
if (length1 < length2) {
for (int i = 0; i < length1; i++) {
if (word1[i] < word2[i]) {
return -1;
} else if (word1[i] > word2[i]) {
return 1;
} else if (i == length1 - 1) {
// If I'm here then it means that all of the characters
// from 0 to length1-1 are equals
// but since length of the first string is shorter than the second,
// the first string will be put before the second
return -1;
}
}
}
if (length1 > length2) {
for (int i = 0; i < length2; i++) {
if (word1[i] < word2[i]) {
return -1;
} else if (word1[i] > word2[i]) {
return 1;
} else if (i == length1 - 1) {
return 1;
}
}
}
return -999;
}
public static void main(String[] args) {
char[] share = { 's', 'h', 'a', 'r', 'e' };
char[] ship = { 's', 'h', 'i', 'p' };
System.out.println(lexico(share, ship)); // -1 share is before ship
System.out.println(lexico(ship, share)); // 1 ship is after share
System.out.println(lexico(ship, ship)); // 0 same word
}
答案 0 :(得分:2)
一些注意事项:
您只需要一个循环:从两个长度的开头到下限。如果直到两个长度中的较小者为止的数组都是相同的,并且它们的长度不同,则您的分配应告诉您要返回什么(通常,如果左侧数组短于右侧,则返回-1,否则返回1)。 / p>
a < b
不是两个字符的有效字母比较(大多数程序员在说“词典”时表示的意思,“ lexico”的意思是“与单词有关”),它是一个数字比较。现在,String
的{{3}}声称使用“字典顺序”,但实际上只使用数字顺序,因此对于您正在做的事情可能已经足够了。如果要按字母顺序排序,我想不出一个JDK比较方法,该方法接受两个单个的 chars 进行比较而不是字符串。可能我不认识一个,或者您可能必须创建一个字符的字符串来进行比较(使用compareTo
),例如,它将正确地识别出à
“voilà”中的“”应该位于其中的其他字母之前。
答案 1 :(得分:-2)
好吧,我放弃了并写下了它……没有任何单元测试(总是交付代码为Unit Tested),但是我认为这应该给您一个功能上工作的好主意(有诸如长度不同的边缘情况,等等)。处理过,但您的想法正确吗?)...欢呼,玩得开心:=)...我猜可以用流更有效地完成它...
public static void main(String[] args) {
List<Character> firstCharArr = new ArrayList<>(Arrays.asList('a', 'c'));
List<Character> secondCharArr = new ArrayList<>(Arrays.asList('x', 'c'));
BiFunction<Character, Character, Integer> charCompareFunction = new BiFunction<Character, Character, Integer>() {
@Override
public Integer apply(Character character, Character character2) {
if (character.charValue() < character2.charValue()) {
return -1;
} else if (character.charValue() == character2.charValue()) {
return 0;
} else {
return 1;
}
}
};
int i = 0;
for (Character firstLineChar : firstCharArr) {
if (charCompareFunction.apply(firstLineChar, secondCharArr.get(i++)) == 0) {
continue;
} else {
if (charCompareFunction.apply(firstLineChar, secondCharArr.get(i++)) < 0) {
System.out.println("FirstLine is Smaller");
break;
} else {
System.out.println("FirstLine is Larger");
break;
}
}
}
}
实际上,您可以使用上面的代码,证明Java的字符词典顺序: 字母前的数字 小写之前的大写