題目鏈接: https://leetcode.com/problems/unique-substrings-in-wraparound-string/description/
Description
Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s
will look like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.
Now we have another string p
. Your job is to find out how many unique non-empty substrings of p
are present in s
. In particular, your input is the string p
and you need to output the number of different non-empty substrings of p
in the string s
.
Note: p
consists of only lowercase English letters and the size of p might be over 10000.
Example 1:
Input: "a"
Output: 1
Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:
Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in the string s.
Example 3:
Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
解題思路
整體思路爲動態規劃,先舉幾個例子來看看。
從最簡單的例子開始,p = "acb"
。p
中沒有長度超過 2 的子串是 s
的子串,只有單字符子串 "a", "c", "b"
,共 3 個。
稍微複雜一點點的,p = "abc"
。p
正好是 s
的子串,則 p
的任意子串都是 s
的子串,分別爲 "a", "b", "ab", "c", "bc", "abc"
,可以看到 a
結尾的子串有 1 個,b
結尾的子串有 2 個,c
結尾的子串有 3 個。
再稍微複雜一點點的,p = "ababc"
。此時,p
不是 s
的子串,但是 p
中有一個子串 ab
是另一個子串 abc
的子串,存在包含關係,那麼 p
中能匹配到 s
的非空子串數量由更長的子串 abc
決定。
總結上面這些例子,若 p
中有一個能匹配到 s
的長度爲 t
的連續子串,則以子串中每個字符爲結尾的子串個數分別爲 1, 2, ..., t
,並且若有另一個包含該子串的更長的子串,則以更長的子串爲主。
因此,算法的具體實現爲先創建一個長度爲 26 的數組用來記錄每個字符爲結尾的子串最多有多少個,最後將該數組每一項相加即爲結果。
時間複雜度 O(n)
, 空間複雜度 O(1)
。
Code
class Solution {
public:
int findSubstringInWraproundString(string p) {
vector<int> alpha(26, 0);
int maxLen, res = 0;
for (int i = 0; i < p.size(); ++i) {
if (i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25))
maxLen++;
else
maxLen = 1;
alpha[p[i] - 'a'] = max(alpha[p[i] - 'a'], maxLen);
}
for (auto x: alpha) res += x;
return res;
}
};