如何使用O(n)时间复杂度算法找到有效subString的数量

时间:2018-06-07 10:11:06

标签: java algorithm substring time-complexity complexity-theory

所以我需要一个接收String类型变量,char类型变量和int类型变量的java方法:

public static int subStrMaxC(String s, char c, int k)

所以这个方法的想法是检查String中以字符c开头和结尾的子串的数量,并在其中包含最多的k个字符。 同时使用O(n)的时间复杂度n == s.length() 添加以下API文档:

/**
     * Checks how many Sub-Strings are within a given String that starts and ends with a given character and also has that character inside the Sub-String maximum a given amount of times.
     * @param s the String to check for the Sub-String within.
     * @param c the character to check the Sub-String according to.
     * @param k the amount of time that the given character has to be within every Sub-String.
     * @return the number of the valid Sub-Strings.
     * @timeComplexity O(n) n - the String's (s) length.
     * @SpaceComplexity O(1)
     */

例如:     subStrMaxC(“abcabcabc”,“c”,1); 应该返回3,因为有效的subString是: “cabc”,“cabc”,“cabcabc”

这是我的代码,但它没有返回正确的答案:

public static int subStrMaxC(String s, char c, int k) {
    int count = 0, toReturn = 0;
    for(int index = 0; index < s.length(); index++) {
        if(s.charAt(index) == c)
            count++;
    }

    while(k >= 0) {
        if(k == 0)
            return toReturn;
        else if(k % 2 == 0) {
            toReturn += count - (k + 1) - toReturn;
            k--;
        }
        else {
            toReturn += count / 2 - toReturn;
            k--;
        }
    }
    return toReturn;
}

很想得到一些帮助!谢谢!

1 个答案:

答案 0 :(得分:2)

我们需要做一些观察才能解决这个问题:

假设我们拥有以索引ith结尾的最长有效子字符串,其中包含x个字符cx <= k,因此,它总共包含{ {1}}字符x + 2。我们可以这么说,任何以此索引c结尾并从任何第一个ith字符开始的子字符串都是有效的子字符串。

因此,对于字符串中的每个字符x+1,我们只需要找到它前面的字符c(表示为c)的数量,如果它大于{ {1}},只需在结果中添加count,否则只需添加k + 1

所以这是伪代码:

k + 1

时间复杂度:O(n)

工作演示:https://ideone.com/aUpxk5