【问题标题】:How to write a program that returns number of occurrences of a string in another string? [closed]如何编写一个程序,返回一个字符串在另一个字符串中出现的次数? [关闭]
【发布时间】:2016-07-02 16:01:56
【问题描述】:

所以我是编程新手。我正在使用java。现在我有一个作业在教 java 的网站上无法解决。

这是作业

编写一个程序,返回一个字符串在另一个字符串中出现的次数。

例如

输入:

第一个字符串:

第二个字符串:学生们在工程学院努力工作,因为他们喜欢它 输出:

3

注意:您应该只使用嵌套循环。不要使用 indexOf 或 substring 之类的方法。

Ienter image description here 到达代码计算出现次数但在重复字母的情况下失败

例如

输入:

第一个字符串:ooo

第二个字符串:wooooooooooooooooooooow

输出:21

应该是 7,因为 ooo 只重复了 7 次

【问题讨论】:

  • 欢迎来到 StackOverflow。请花一些时间访问help center 并阅读How to Ask。您的问题是题外话,因为您要求我们为您编写代码。 StackOverflow 不是讨论、教程或代码编写站点。这样做的方式是您应该尝试解决方案,然后在遇到问题时寻求帮助,清楚地解释您尝试过的内容以及您不理解的内容。

标签: java string


【解决方案1】:

这个问题可以用z-function在线性时间内简单地解决。

int NumberOfcopies(String t, String h){
    // t = the first string i.e "ooo"
    // h = the second string i.e "wooooooooooooooooooooow"

    String s = t + "$" + h; // adding a sentinel character in between
    int n = s.length(); // length of new string
    int[] z = new int[n]; // z array

    // Code ref : http://e-maxx-eng.github.io/string/z-function.html
    int l = 0, r = 0;
    for (int i = 1; i < n; i++){
        if (i <= r)
            z[i] = Math.min(r - i + 1, z[i - 1]);
        while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
            ++z[i];
        if (i + z[i] - 1 > r){
            l = i;
            r = i + z[i] - 1;
        }
    }

    //checking for all the occurance of string t in string h
    int res = 0;
    for (int i = t.length() + 1; i < n; ){
        if (z[i] == t.length()){
            //A copy is found so skip next t.length chars
            i += t.length();
            ++res; 
        }
        else ++i;
    }
    System.out.println("Number of Occurance : " + res);
    return res;
}

这个字符串的 Z 函数是一个长度为 n 的数组,其中 i-th 元素等于最大字符数 从与第一个重合的位置 i 开始 s的字符。

这可以被利用来查找字符串 t 在另一个字符串 h 中出现的次数。假设我们在字符串 t 和 h 之间加入一个标记字符(标记字符是两个字符串中都没有出现的字符)以形成一个新字符串 s

让我们计算数组z[]中的z函数。

现在让我们从标记字符之后的字符开始搜索,即字符串 h 的字符。对于字符串 h 中的第 i 个字符(使得第 i 个字符属于字符串 s)如果 z[i] 等于字符串 t 的长度(模式),那么它意味着从第 i 个字符开始,t.length() 字符与字符串 s 的第一个 t.length() 字符相同,即字符串 t 的含义。

示例:
t = ab
h = aaabaab

s = a b $ a a a b a b
z = 0 0 0 1 1 2 0 1 2 0
我 = 0 1 2 3 4 5 6 7 8 9

对于i = 5,我们可以看到z[i] == t.length(),这意味着我们找到了一个副本。现在为了防止重叠解决方案,我们跳过 t.length() 字符,因此现在是 i = 7

继续这样做会得到结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多