有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计数字符串中非重叠出现的次数

您好,我正在尝试解决一个问题,在这个问题中,我计算字符串s1中不重叠的字符串s2的出现次数。示例String s1 = "abab"String s2 = "ab"出现的次数为2。另一个例子String s1 = "aaabbaa"String s2 = "aa"出现的次数是2。最后一个示例,如果String s1 = "aabbaa"String s2 = "AA"出现的次数等于0。 我该如何处理这个问题

想法: 我知道我是否匹配s1中的字符串s2。通过将当前索引位置与s2相加,我移动到下一个位置。长度,如果它们不相等,则将当前索引位置增加1。我的问题不知道如何开始?您将如何使用迭代来解决这个问题。谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    我希望这是不言自明的(使用String.indexOf):

    public int countOccurrences(String haystack, String needle) {
      int count = 0, offset = 0, index;
      // As long as there is another occurrence...
      while((index = haystack.indexOf(needle, offset)) != -1) {
        // Skip already matched parts the next time
        offset = index + needle.length();
        // Increment counter
        count++;
      }
      return count;
    }
    

    Edit:@JennFitz请求了一个递归版本,所以它在这里(尽管上面的方法更好):

    public int countOccurrences(String haystack, String needle) {
      int index = haystack.indexOf(needle);
      if(index == -1) return 0;
      int offset = index + needle.length();
      return 1 + countOccurrences(haystack.substring(offset), needle);
    }