LeetCode Statistics of Beautiful Substrings II [Prime Factorization, Prefix Sum, Hash Table] Difficulty

This article belongs to one of the series of articles "Conquering LeetCode". This series officially started on 2021/08/12. Since some questions on LeetCode are locked, this series will continue at least until all unlocked questions are cleared; since LeetCode is still creating new questions, the end date of this series may be forever. In this series of problem-solving articles, I will not only explain various problem-solving ideas and their optimization, but also use a variety of programming languages ​​to solve the problems. When it comes to general solution methods, I will also summarize the corresponding algorithm templates.

In order to facilitate running, debugging and sharing code files on PC, I also established a related warehouse: https://github.com/memcpy0/LeetCode-Conquest . In this warehouse, you can not only see the link to the original LeetCode question, solution code, link to the solution article, summary of similar questions, summary of common solutions, etc., but also important information such as the frequency of original questions and related companies. If you have other preferred solutions, you can share them with others.

Since the content of this series of articles may be updated and changed at any time, you are welcome to follow and save the article Table of Contents of the Conquering LeetCode series of articles as a reminder.

You are given a string  s and a positive integer  k .

Use  vowels and  consonants to represent the number of vowels and consonants in the string respectively.

A string is called a beautiful string if it satisfies the following conditions   :

  • vowels == consonants, that is, the number of vowels and consonants is equal.
  • (vowels * consonants) % k == 0, that is, the product of the number of vowels and consonants can be  k divisible.

Returns  the number of s non-  empty beautiful substrings in a string  .

A substring is a contiguous sequence of characters in a string.

The vowels in English   are  'a', 'e', 'i', 'o' and  'u' .

Consonants in English   are all letters except vowels.

Example 1:

输入:s = "baeyh", k = 2
输出:2
解释:字符串 s 中有 2 个美丽子字符串。
- 子字符串 "b_aeyh_",vowels = 2["a","e"]),consonants = 2["y","h"])。
可以看出字符串 "aeyh" 是美丽字符串,因为 vowels == consonants 且 vowels * consonants % k == 0- 子字符串 "_baey_h",vowels = 2["a","e"]),consonants = 2["b","y"])。
可以看出字符串 "baey" 是美丽字符串,因为 vowels == consonants 且 vowels * consonants % k == 0
可以证明字符串 s 中只有 2 个美丽子字符串。

Example 2:

输入:s = "abba", k = 1
输出:3
解释:字符串 s 中有 3 个美丽子字符串。
- 子字符串 "_ab_ba",vowels = 1["a"]),consonants = 1["b"])。
- 子字符串 "ab_ba_",vowels = 1["a"]),consonants = 1["b"])。
- 子字符串 "_abba_",vowels = 2["a","a"]),consonants = 2["b","b"])。
可以证明字符串 s 中只有 3 个美丽子字符串。

Example 3:

输入:s = "bcdf", k = 1
输出:0
解释:字符串 s 中没有美丽子字符串。

hint:

  • 1 <= s.length <= 5 * 10^4
  • 1 <= k <= 1$0$
  • s Consists of only lowercase English letters.

Solution: decompose prime factors + prefix sum + hash table

Treat vowels as 1 11 , consonants are treated as− 1 -1−1 . _ "The number of vowels and consonants is equal" is equivalent to:Find a sum that sums to 0 0contiguous subarray of 0. Note that the length of this subarray must be an even number , because the number of vowels and consonants is equal.

Let the length of the subarray be LLL. _ Since the number of vowels and consonants is equal,the number of vowels and consonants is equal to L 2 \dfrac{L}{2}2L, so "the product of the number of vowels and consonants can be kk"Divisible by k " is equivalent to
( L 2 ) 2 mod k = 0 \left(\dfrac{L}{2}\right)^2 \bmod k = 0(2L)2modk=0This
is equivalent to
L 2 mod (4 k) = 0 L^2 \bmod (4k) = 0L2mod( 4k ) _=The square of 0
is very annoying. It would be easier if the square could be removed.

There has to be some math here . Let’s study it. If a number LLThe square of L can be given by nnWhat does it mean to be divisible by n ?

  • Assume nn is a prime number, such as3 33 , thenLLL must contain prime factors3 33 , at this point the question becomes: determineLLCan L be 3 3Divisible by 3 . We took out the square!
  • if nnn is the eeof a prime number $pWhat about e power? Classification discussion:
    • ifee _e is an even number, such asn = 3 4 n=3^4n=34 , thenLLL must contain factors3 2 3^232 , so thatL 2 L^2L2 can benn is divisible. At this point the question becomes: determineLLCan L be 3 2 3^23Divisible by 2 .
    • ifee _e is an odd number, such asn = 3 5 n=3^5n=35 , thenLLL must contain factors3 3 3^333 , so thatL 2 L^2L2 can benn is divisible. At this point the question becomes: determineLLCan L be 3 3 3^33Divisible by 3 .
      SoLLL must contain the factorprp^rpr ,其中 r = ⌈ e 2 ⌉ = ⌊ e + 1 2 ⌋ r=\left\lceil\dfrac{e}{2}\right\rceil = \left\lfloor\dfrac{e+1}{2}\right\rfloor r=2e=2e+1
  • if nnn can be decomposed into multiple prime factors. You only need to process each prime factor and its power according to the above method, and then multiply them to getLLWhat factors must L contain?

Continue
to put 4 44 Calculate according to the above method, assumingLLL must contain factorsk ′ k'k . Now the question becomes, how many sums are0 0A subarray of 0 whose length isk ′ k'kMultiples of ′ ?

Let the subscript range of the subarray be [ j , i ) [j,i)[j,i ) , then its lengthL = i − j L=ijL=ij , then
( i − j ) mod k ′ = 0 (ij)\bmod k' = 0(ij)modk=0
is equivalent to
i mod k ′ = j mod k ′ i \bmod k' = j\bmod k'imodk=jmodk
For the element sum, it is equivalent tos [ i ] − s [ j ] = 0 s[i]-s[j] = 0s[i]s[j]=0 ,即
s [ i ] = s [ j ] s[i] = s[j] s[i]=s [ j ]
we need to satisfy both conditions (subscript modulok ′ k'k Equal,sss values ​​are equal), this can be solved with a hash table. The key key of the hash tablek ey is apair pairpair ( i   m o d   k ′ , s [ i ] ) (i\bmod k', s[i]) (imodk,s [ i ]) ,the value valuev a l u e is thispair pairThe number of occurrences of p ai r .

When implementing the code, the prefix and array can be represented by a variable .

When implementing the code, it can be aeioucompressed into a binary number to quickly determine whether the letter is a vowel .

Question: Why does the hash table insert a ( k ′ − 1 , 0 ) (k'-1, 0) at the beginning?(k1,0 ) ?
Answer: The first term of the prefix sum is0 00 , since the code is from subscript0 0The second prefix sum starts from 0 , so it is equivalent to s [ − 1 ] = 0 s[−1]=0s[1]=0 , whilek ′ − 1 k'-1k1 and− 1 -11 aboutk ′ k'k is congruent, so insert( k ′ − 1 , 0 ) (k′−1,0)(k1,0)

class Solution {
    
    
private:
    int pSqrt(int n) {
    
    
        int ans = 1;
        for (int i = 2; i * i <= n; ++i) {
    
    
            int i2 = i * i;
            while (n % i2 == 0) {
    
     // 质因数分解
                ans *= i; // L必须包含一个i^1
                n /= i2;
            }
            if (n % i == 0) {
    
     // 如果n包含某个质数的奇次幂
                ans *= i;
                n /= i;
            }
        }
        if (n > 1) ans *= n; // 剩下的最后1个质因子
        return ans;
    }
    struct PairHash {
    
    
        template<typename T1, typename T2>
        size_t operator() (const pair<T1, T2> &p) const {
    
    
            auto v1 = std::hash<T1>{
    
    }(p.first);
            auto v2 = std::hash<T2>{
    
    }(p.second);
            return v1 ^ v2;
        }
    };
    unordered_map<pair<int, int>, int, PairHash> cnt; //ok
public:
    int beautifulSubstrings(string s, int k) {
    
    
        k = pSqrt(k * 4); // 4k的质因数分解,求出L必须包含的因子值(多个质因子的幂次的乘积)
        const int aeiouMask = 1065233;
        cnt[ pair<int, int>{
    
     k - 1, 0} ] = 1; // k-1和1同余
        int sum = 0;
        int ans = 0;
        for (int i = 0; i < s.size(); ++i) {
    
    
            char c = s[i];
            int bit = aeiouMask >> (c - 'a') & 1;
            sum += bit * 2 - 1; // 1->1, 0->-1
            auto p = pair{
    
    i % k, sum};
            ans += (long long)cnt[p];
            ++cnt[p];
        }
        return ans;
    }
};

Complexity analysis:

  • Time complexity: O ( n + k ) \mathcal{O}(n + \sqrt k)O ( n+k ) , wherennn nums \textit{nums} The length of nums .
  • Space complexity: O ( n ) \mathcal{O}(n)O ( n )

Guess you like

Origin blog.csdn.net/myRealization/article/details/134634359