[LeetCode] Unique Substrings in Wraparound String

467. Unique Substrings in Wraparound String

We define the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this:

  • “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.

Given a string p, return the number of unique non-empty substrings of p are present in s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
bool isNext(char prev, char next) {
return next == 'a' ? prev == 'z' : next == prev + 1;
}
public:
int findSubstringInWraproundString(string p) {
unordered_map<char, int> m;
int maxLen = 1;
m[p[0]] = maxLen;
for(int i = 1; i < p.length(); i++) {
maxLen = isNext(p[i - 1], p[i]) ? maxLen + 1 : 1;
m[p[i]] = max(maxLen, m[p[i]]);
}
return accumulate(m.begin(), m.end(), 0, [](const int prev, const pair<const char, int>& p) { return prev + p.second; });
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/17/PS/LeetCode/unique-substrings-in-wraparound-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.