提问人:Miguel Barra 提问时间:1/30/2022 最后编辑:azroMiguel Barra 更新时间:1/30/2022 访问量:370
HackerRank 上的 Java 子字符串比较中的测试用例 2 失败
Test Case 2 failure in Java Substring Comparisons on HackerRank
问:
它通过了除测试用例 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
答:
-1赞
rentox98
1/30/2022
#1
似乎在 for 循环中,您创建子字符串并仅比较第一个字符,因此例如,在迭代中,您可以有 largest = “ffooo” 和 output = “foooo”,但在这种情况下,程序跳过条件并失败(保留错误的最大子字符串)。 您必须考虑这种情况。
评论