Skip to content

2223. Sum of Scores of Built Strings

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  long long sumScores(string s) {
    const int n = s.length();
    // https://cp-algorithms.com/string/z-function.html#implementation
    vector<int> z(n);
    // [l, r] := the indices of the rightmost segment match
    int l = 0;
    int r = 0;

    for (int i = 1; i < n; ++i) {
      if (i < r)
        z[i] = min(r - i, z[i - l]);
      while (i + z[i] < n && s[z[i]] == s[i + z[i]])
        ++z[i];
      if (i + z[i] > r) {
        l = i;
        r = i + z[i];
      }
    }

    return accumulate(z.begin(), z.end(), 0L) + n;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public long sumScores(String s) {
    final int n = s.length();
    // https://cp-algorithms.com/string/z-function.html#implementation
    int[] z = new int[n];
    // [l, r] := the indices of the rightmost segment match
    int l = 0;
    int r = 0;

    for (int i = 1; i < n; ++i) {
      if (i < r)
        z[i] = Math.min(r - i, z[i - l]);
      while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
        ++z[i];
      if (i + z[i] > r) {
        l = i;
        r = i + z[i];
      }
    }

    return Arrays.stream(z).asLongStream().sum() + n;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def sumScores(self, s: str) -> int:
    n = len(s)
    # https://cp-algorithms.com/string/z-function.html#implementation
    z = [0] * n
    # [l, r] := the indices of the rightmost segment match
    l = 0
    r = 0

    for i in range(1, n):
      if i < r:
        z[i] = min(r - i, z[i - l])
      while i + z[i] < n and s[z[i]] == s[i + z[i]]:
        z[i] += 1
      if i + z[i] > r:
        l = i
        r = i + z[i]

    return sum(z) + n