【发布时间】:2020-02-24 00:54:37
【问题描述】:
问题陈述:
给定一个字符串 s 和一个整数 k,完成函数,以便找到长度为 k 的字典上最小和最大的子字符串。
代码:
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
String substring = s.substring(0, k);
String smallest = substring;
String largest = substring;
for (int i = 1; i <= s.length() - k; i++) { //This line
// Create a substring of length 'k'
substring = s.substring(i, i + k);
// If current substring is lexicographically smaller than 'smallest'
if (substring.compareTo(smallest) < 0) {
smallest = substring;
}
// If current substring is lexicographically larger than 'largest'
if (substring.compareTo(largest) > 0) {
largest = substring;
}
}
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));
}
}
我无法理解代码中标记行的机制。有人可以向我解释吗?
【问题讨论】: