首页 > 解决方案 > 查找字符串中的模式计数(包括重叠)

问题描述

所以我正在尝试编写一个算法来计算某个模式的出现次数,比如“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);

}

}

有什么建议么?

标签: java

解决方案


在这种情况下,我个人会将模式作为子字符串进行比较。例如,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 次出现


推荐阅读