題目連結

想想看,與其窮舉所有的 substring ,我們改成: 對於每一個 $S[i] $,看看有哪些子字串計算unique時會算到 $S[i]$!

對於每一個 $S[i]$,我們找出他的最遠左右端點,端點內的 $S[j]$ 要符合 $S[i] \neq S[j]$ 且 $0 <= j < S.length()$。因此,我們可以輕鬆得到包含 $S[i]$ 的 substring 會有 $(i - left + 1) * (right - i + 1)$ 個啦!

AC Code

 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
56
57
58
59
60
61
62
63
64
65
66
67
68
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// tree node stuff here...
#endif

static int __initialSetup = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}
();

// handle special cases first
// [], "", ...
// range of input?
const int MOD = 1e9 + 7;
class Solution
{
private:
    void inc(long long &ans, int amount)
    {
        ans = (ans + amount) % MOD;
    }

public:
    int uniqueLetterString(string S)
    {
        int n = S.length();
        long long ans = 0;
        for (int i = 0; i < n; i++) {
            int lb = i, rb = i;
            bool doneL = false, doneR = false;
            for (int j = 1; j < n; j++) {
                if (doneL == false && i - j >= 0) {
                    if (S[i] != S[i - j]) {
                        lb = i - j;
                    } else {
                        doneL = true;
                    }
                }

                if (doneR == false && i + j < n) {
                    if (S[i] != S[i + j]) {
                        rb = i + j;
                    } else {
                        doneR = true;
                    }
                }
            }

            inc(ans, (i - lb + 1) * (rb - i + 1));
        }

        return ans;
    }
};

#ifdef LOCAL
int main()
{
    cout << Solution().uniqueLetterString("ABC") << endl;
    return 0;
}
#endif