java - 查找字符串中的模式计数(包括重叠)
问题描述
所以我正在尝试编写一个算法来计算某个模式的出现次数,比如“aa”,在一个字符串中,比如“aaabca”。该字符串中的模式数应返回一个整数,在本例中为 2,因为前三个字符包含两次出现的模式。
在假设模式的现有出现不重叠的情况下,我发现了模式的数量:
public class Pattern{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string: ");
String s = scan.nextLine();
String[] splittedInput = s.split(";");
String pattern = splittedInput[0];
String blobs = splittedInput[1];
Pattern p = new Pattern();
p.count(pattern, blobs);
}
public static void count(String pattern, String blobs){
String[] substrings = blobs.split("[|]");
int numOccurences = 0;
int[] instances = new int[substrings.length];
int patternLength = pattern.length();
for (int i = 0; i < instances.length; i++){
int length = substrings[i].length();
String temp = substrings[i];
temp = temp.replaceAll(pattern, "");
int postLength = temp.length();
numOccurences = (length - postLength) / pattern.length();
instances[i] = numOccurences;
numOccurences = 0;
}
int sum = 0;
for (int i = 0; i < instances.length; i++){
System.out.print(instances[i] + "|");
sum += instances[i];
}
System.out.print(sum);
}
}
有什么建议么?
解决方案
在这种情况下,我个人会将模式作为子字符串进行比较。例如,String
从您的数组中运行一个单曲将如下所示:
//Initial values
String blobs = "aaaabcaaa";
String pattern = "aab";
String[] substrings = blobs.split("[|]");
//The code I added that should placed into the loop
int numOccurences = 0;
String str = substrings[0];
for (int k = 0; k <= (str.length() - pattern.length()); k++)
{
if (str.substring(k, k + pattern.length()).equals(pattern))
{
numOccurences++;
}
}
System.out.println(numOccurences);
如果你想String
在你的数组中的每一个上运行它,只需修改String str = substrings[0]
并String str = substrings[i]
迭代存储numOccurences
你喜欢的最终数组的数组。
示例运行:
字符串是 aaaabcaaa
模式是 aa
输出为 5 次出现
推荐阅读
- eclipse - Eclipse 断点 - 如何在每次调试检查后停止自动禁用
- laravel - 两个日期的 Laravel 自定义验证
- scala - 如何将元组的 Seq 转换为单个元素的集合 Scala
- c - printf("%.0f\n", nc) 没有打印意图信息
- reactjs - React-Loadable 与第三方反应组件不起作用
- json - Flutter 使用来自 Golang RFC3339 的 DateTime 解析 json:FormatException:无效的日期格式
- game-maker - 球在乒乓克隆中卡在桨内(游戏制作者)
- swift - 在 Swift 中,协议扩展是否允许函数体?
- r - ggplot2中的中值回归线
- php - 计算更换零件的运行小时数