We are given a string p
consisting of lowercase English letters. Suppose we have a string ‘s’ that consists of the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s
looks like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd…”.
We need to determine the number of unique non-empty substrings of p
that are substrings of s
.
p
?
p
can be up to 10,000.p
that are outside the range ‘a’ to ‘z’?
p
consists only of lowercase English letters.dp
where dp[c]
stores the maximum length of the substring ending with character c
.p
, for each character, update the lengths of substrings that fit the wraparound condition.p
, check if it is the next character in the wraparound sequence of the previous character.dp
array with the maximum length found for each endpoint character.dp
array, giving the count of unique substrings.def findSubstringInWraproundString(p: str) -> int:
if not p:
return 0
dp = {chr(i): 0 for i in range(ord('a'), ord('z') + 1)}
max_len_current = 0
for i in range(len(p)):
if i > 0 and (ord(p[i]) - ord(p[i - 1]) == 1 or ord(p[i - 1]) - ord(p[i]) == 25):
max_len_current += 1
else:
max_len_current = 1
dp[p[i]] = max(dp[p[i]], max_len_current)
return sum(dp.values())
# Example usage
p = "zab"
print(findSubstringInWraproundString(p)) # Output should be 6
n
is the length of the string p
. Each character of the string is processed exactly once.dp
array stores a fixed number of characters (26 letters in the alphabet), resulting in constant space usage.This ensures an efficient calculation of the number of unique substrings that fit the given conditions.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?