Leetcode-3333

Find the Original Typed String II

Time complexity: $O(nk)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <cstring>

const int M = 1'000'000'007;

class Solution {
public:
    int possibleStringCount(std::string word, int k) {
        long long tot = 1;
        int len = 0;
        char prev = word[0];
        dp[0] = 1;
        int cnt = 0;
        
        for (char c : word) {
            if (c == prev) {
                ++len;
            }
            else {
                tot = (tot * len) % M;
                ++cnt;
                if (cnt < k) {
                    process(len, k);
                }
                len = 1;
                prev = c;
            }
        }
        tot = (tot * len) % M;
        if (cnt >= k) {
            return tot;
        }
        
        process(len, k);
        for (int i : dp) {
            tot = (tot + M - i) % M;
        }
        
        return tot;
    }
    
private:
    void process(int len, int k) {
        std::swap(dp, tmp);
        dp[0] = 0;
        for (int i = 1; i < k; ++i) {
            dp[i] = (dp[i - 1] + tmp[i - 1]) % M;
            if (i - len > 0) {
                dp[i] = (dp[i] + M - tmp[i - len - 1]) % M;
            }
        }
    }
    
    int dp[2001] = { 0 }, tmp[2001];
};

Leetcode-3333

Licensed under CC BY-NC-SA 4.0