
在图像中,当对字符串数组进行排序时,我不明白多余的O从何而来。我得到排序的字符串数组将是O(log a),我不明白为什么我们也必须添加O(s)。
在我看来,O(a log a)负责整理字符串数组中的所有字符串。
本题来自破解编码面试第 6 版,第 V1.11 题。
以下代码打印所有长度为 k 的字符串,其中字符按排序顺序。它通过生成所有长度为 k 的字符串然后检查每个字符串是否已排序来实现。什么是运行时?
package QVI_11_Print_Sorted_Strings;
public class Question {
public static int numChars = 26;
public static void printSortedStrings(int remaining) {
printSortedStrings(remaining, "");
}
public static void printSortedStrings(int remaining, String prefix) {
if (remaining == 0) {
if (isInOrder(prefix)) {
System.out.println(prefix);
}
} else {
for (int i = 0; i < numChars; i++) {
char c = ithLetter(i);
printSortedStrings(remaining - 1, prefix + c);
}
}
}
public static boolean isInOrder(String s) …Run Code Online (Sandbox Code Playgroud)