【问题标题】:Comparing Strings lexicographically new approach fails for one test case一个测试用例按字典顺序比较字符串的新方法失败
【发布时间】:2017-09-06 09:57:54
【问题描述】:

我被要求检查String a 在字典上是否大于String b。所以甚至在考虑compareTo() 方法之前,我就有了一个新想法。

  1. 取 a 和 b 长度中的最小值。
  2. 迭代一个 for 循环直到最小长度,并将每个字符的 ascii 的总和分别存储在 a 和 b 中。
  3. 比较ascii 以打印结果。

这是我的代码

private static void isInLexicographicOrder(String a, String b) {
    char[] arr1 = a.toCharArray();
    int asciCount1 = 0;

    char[] arr2 = b.toCharArray();
    int asciCount2 = 0;

    long asciLength = (a.length() < b.length()) ? a.length() : b.length();
    for(int i=0; i<asciLength; i++) {
        asciCount1 += arr1[i];
        asciCount2 += arr2[i];
    }

    if(asciCount1 < asciCount2) {
        System.out.println("In Lexicographic Order");
    }
    else {
        System.out.println("Not In Lexicographic Order");
    }

}

我提供的许多输入都可以正常工作,然后我找到了这个链接String Comparison in Java,所以为了确认我在我的代码中使用了比较方法。

System.out.println((a.compareTo(b)) < 0 ? "In Lexicographic Order" : "Not In Lexicographic Order");

现在当我提交代码时,另一个网站说代码在一个测试用例中失败

示例输入

vuut
vuuuuu

他们希望输出为No,即Not In Lexicographic Order。但我的逻辑和compareTo() 逻辑说In Lexicographic Order。那么怎么了,我的逻辑完全正确吗?

这是我获得Question. 的链接,如果我错了,抱歉

【问题讨论】:

    标签: java string string-comparison compareto lexicographic


    【解决方案1】:

    comareTo 方法迭代两个字符串的字符,直到到达两个字符不同的位置。返回值是两个代码点值之间的差异。

    您的实现将所有代码点加到一个总和中,并返回此加法结果的差。

    尝试使用值abcddcba 的方法。我希望您的方法返回 0 而不是负数

    【讨论】:

    • 很好的比较(双关语)。但是,您的术语是错误的。正在比较的是 UTF-16 代码单元。考虑一下,"?".compareTo("*")) == "?".compareTo("*")) 因为? 和?各有两个代码单元,第一个相同,而 * 有一个。因此,它们与 * 不同,因为同一点因此 compareTo 返回相同的数字。
    【解决方案2】:

    你的逻辑不正确。比较字符的总和是错误的,因为“bab”、“abb”和“bba”将具有相同的值,但这并不能说明它们中的哪一个在字典上排在第一位。

    您应该分别比较每对字符。第一次遇到不相等的一对字符时,值较小的属于应该先出现的字符串。

    for(int i=0; i<asciLength; i++) {
        if (arr1[i] > arr2[i]) {
            System.out.println("Not In Lexicographic Order");
            return;
        } else if (arr1[i] < arr2[i]) {
            System.out.println("In Lexicographic Order");
            return;
        }
    }
    // at this point we know that the Strings are either equal or one 
    // is fully contained in the other. The shorter String must come first
    if (arr1.length <= arr2.length) {
        System.out.println("In Lexicographic Order");
    } else {
        System.out.println("Not In Lexicographic Order");
    } 
    

    【讨论】:

    • 是的,我有这种感觉,我哪里错了
    • 但是我提供的示例输入,它是按字典顺序排列的吧?
    • @ArunSudhakaran 是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多