【问题标题】:Test Case 2 failure in Java Substring Comparisons on HackerRankHackerRank 上 Java 子字符串比较中的测试用例 2 失败
【发布时间】:2022-01-29 21:06:27
【问题描述】:

它通过了除测试用例 2 和 4 之外的所有用例。这是我的代码:

import java.util.Scanner;

public class Solution {

    public static String getSmallestAndLargest(String s, int k) {
        String smallest = "";
        String largest = "";
        
        // Complete the function
        // 'smallest' must be the lexicographically smallest substring of length 'k'
        // 'largest' must be the lexicographically largest substring of length 'k'
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int len = s.length() - k;
        for (int i = 0; i <= len; i++) {
            String output = s.substring(i, k++);
            int ascii_code_1 = output.charAt(0);
            int ascii_code_2 = output.charAt(0);
            if (ascii_code_1 < min) {
                min = ascii_code_1;
                smallest = output;
            }
            if (ascii_code_2 > max) {
                max = ascii_code_2;
                largest = output;
            }
        }
        
        return smallest + "\n" + largest;
    }


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        int k = scan.nextInt();
        scan.close();
      
        System.out.println(getSmallestAndLargest(s, k));
    }
}

这是测试用例 2:

ASDFHDSFHsdlfhsdlfLDFHSDLFHsdlfhsdlhkfsdlfLHDFLSDKFHsdfhsdlkfhsdlfhsLFDLSFHSDLFHsdkfhsdkfhsdkfhsdfhsdfjeaDFHSDLFHDFlajfsdlfhsdlfhDSLFHSDLFHdlfhs
30

【问题讨论】:

  • 问题是什么?
  • 在“acab”上运行你的代码, 2. 最小的字符串将被给出为“ac”,这显然是错误的。使用调试器逐步检查您的代码以了解原因。

标签: java string algorithm substring comparison


【解决方案1】:

似乎在 for 循环中您创建子字符串并仅比较第一个字符,因此例如在迭代中您可能有最大 = "ffooo" 和输出 = "foooo" 但在这种情况下,程序会跳过条件并失败(保留错误的最大子字符串)。 你必须考虑这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多