467. Unique Substrings in Wraparound String
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.
Approach
- 题目大意就是从p字符串中提取是s的子字符串,子字符串不能重复。这道题真的很巧秒,没点思路真的很难下手,看了大神播客,其实就是计算以每个字母为结尾的最长连续子串长度,然后再统计长度,这样不仅确保了不会重复,还一并计算了组合的问题,真的很佩服这思路。
Code
class Solution {
public:
int findSubstringInWraproundString(string p) {
int n = p.size();
int len = 0;
vector<int>cnt(26, 0);
for (int i = 0; i < n; i++) {
if (i>0&&(p[i - 1] + 1 == p[i] || (p[i - 1] == 'z'&&p[i] == 'a'))) {
len++;
}
else {
len = 1;
}
cnt[p[i] - 'a'] = max(cnt[p[i] - 'a'], len);
}
return accumulate(cnt.begin(), cnt.end(), 0);
}
};
博客围绕计算字符串p在无限循环字符串s中的唯一非空子串数量展开。题目要求从p中提取是s的子字符串且不能重复。解题思路是计算以每个字母为结尾的最长连续子串长度,再统计长度,以此解决组合和重复问题。

2260

被折叠的 条评论
为什么被折叠?



