美文网首页
A general method for substring p

A general method for substring p

作者: MrWheat | 来源:发表于2018-10-14 11:56 被阅读0次

    Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones.
    Examples:
    Input : s = “10010”
    K = 1
    Output : 9
    The 9 substrings containing one 1 are,
    “1”, “10”, “100”, “001”, “01”, “1”,
    “10”, “0010” and “010”

    static int countOfSubstringWithKOnes( 
                                String s, int K) 
        { 
            int N = s.length(); 
            int res = 0; 
            int countOfOne = 0; 
            int []freq = new int[N+1]; 
    
            freq[0] = 1; 
    
            for (int i = 0; i < N; i++) { 
                countOfOne += (s.charAt(i) - '0'); 
                if (countOfOne >= K) { 
                    res += freq[countOfOne - K]; 
                } 
                freq[countOfOne]++; 
            }   
            return res; 
        } 
    

    注意:求子串的时候,尤其是涉及长度,子串里面元素个数之类的问题,可以用类似于动态规划的方法,用当前遍历的值减去之前的值,来找子串,实现复杂度O(n)。
    相似的问题:https://www.geeksforgeeks.org/longest-substring-with-count-of-1s-more-than-0s/

    相关文章

      网友评论

          本文标题:A general method for substring p

          本文链接:https://www.haomeiwen.com/subject/sejzaftx.html