如何有效地手动按字典顺序比较 "abcd" & ""abcde"

How to manually lexicographically compareTo "abcd" & ""abcde" effectively

我想写自己的 compareTo 方法,所以我写了这个简单的代码:

public int myCompare(String a, String b) {
    int min = Math.min(a.length(), b.length());

    for (int i=0; i < min; i++) {
        int diff = a.charAt(i) - b.charAt(i);
        if (diff == 0) {
            continue;
        } else {
            return diff;
        }
    }
    // meaning both strings are equals so far
    if (a.length() == b.length()) {
        return 0;
    } else if (a.length() > b.length()) {
        return -1;
    } else {
        return 1;
    }
}

好吧,这段代码工作正常,但我讨厌最后的 if/else 语句 - 你对如何改进这段代码有什么建议吗?

这取决于你想自己写多少。你可以使用

return a.length() - b.length(); // as length is non-negative

return Integer.compareTo(a.length(), b.length());

在你的第一个循环中你也可以写

for (int i = 0; i < a.length() && i < b.length(); i++) {
    int diff = a.charAt(i) - b.charAt(i);
    if (diff != 0)
        return diff;
}