You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are numbered 1 to n: s_i is the string after i characters have been placed, so s_1 is the last character of s and s_n is s itself.
The score of s_i is the length of the longest common prefix between s_i and s_n (the complete string s).
Given the final string s, return the sum of the scores of every s_i for i from 1 to n.
Function Signature
def sum_scores(s: str) -> int:
Rules
-
s_i
is the suffix of
s
of length
i
, which is
s[n - i:]
in Python slicing.
-
The longest common prefix of two strings is the largest
k
such that their first
k
characters are equal. It is 0 when the first characters differ.
-
s_n
is compared with itself, so its score is
n
.
Constraints
-
1 <= len(s) <= 10^5
-
s
consists of lowercase English letters.
Examples
Input: s = "babab"
Output: 9
The built strings are "b", "ab", "bab", "abab" and "babab". Their longest common prefixes with "babab" are 1, 0, 3, 0 and 5, which sum to 9.
Input: s = "azbazbzaz"
Output: 14
Only three built strings start with "a", the first letter of s, so only they can score: "az" scores 2, "azbzaz" scores 3 (it differs from s at the fourth character) and the full string scores 9. The other six score 0, for a total of 14.
Input: s = "aaa"
Output: 6
Every built string is a run of "a", so each one matches the full string along its whole length: 1 + 2 + 3 = 6.