简体   繁体   English

测试用例 2 失败 Java Substring HackerRank 上的比较

[英]Test Case 2 failure in Java Substring Comparisons on HackerRank

It's passing all cases except for Test Case 2 and 4. This is my code:它通过了除测试用例 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));
    }
}

Here is the Test Case 2:这是测试用例2:

ASDFHDSFHsdlfhsdlfLDFHSDLFHsdlfhsdlhkfsdlfLHDFLSDKFHsdfhsdlkfhsdlfhsLFDLSFHSDLFHsdkfhsdkfhsdkfhsdfhsdfjeaDFHSDLFHDFlajfsdlfhsdlfhDSLFHSDLFHdlfhs
30

It seems that in the for loop you create the substring and compare only the first char, so for instance in an iteration you could have largest = "ffooo" and output = "foooo" but in this case the program skips the conditions and fails (keeping the wrong largest substring).似乎在 for 循环中您创建了 substring 并仅比较第一个字符,因此例如在迭代中您可能有最大 = "ffooo" 和 output = "foooo" 但在这种情况下,程序会跳过条件并失败(保留错误的最大子字符串)。 You must consider this case.你必须考虑这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM