程序分析
计算字符串中子串出现的次数,可以采用多种方法来实现。常见的方法包括暴力法、利用正则表达式和利用KMP算法。
方法一:暴力法
解题思路:
- 在主串中依次遍历每个位置,以该位置为起点,检查是否存在与子串相同的子串。
- 比较简单直观,但时间复杂度较高。
实现代码:
public class SubstringCount {
public static int countSubstring(String str, String sub) {
int count = 0;
int len_str = str.length();
int len_sub = sub.length();
for (int i = 0; i <= len_str - len_sub; i++) {
int j;
for (j = 0; j < len_sub; j++) {
if (str.charAt(i + j) != sub.charAt(j))
break;
}
if (j == len_sub)
count++;
}
return count;
}
public static void main(String[] args) {
</