sop(getCount(s, "kk")); // getCount返回int
private static void sop(String str) { System.out.println(str); } // 參數為String
Java不支持 int 到 String 的隱式轉換,sop 期望 String 實參,實際傳入 int,編譯失敗。
// 方式1:顯式轉字符串
sop(getCount(s, "kk") + "");
// 方式2:重載sop
private static void sop(int i) { System.out.println(i); }
// 方式3:直接用System.out.println
System.out.println(getCount(s, "kk"));
原代碼使用 substring 逐次截取,時間複雜度 O(n²)。改用 indexOf(str, fromIndex) 單次遍歷:
public static int countOccurrences(String text, String sub) {
int count = 0, idx = 0;
while ((idx = text.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
時間複雜度 O(n),避免重複創建字符串對象。