Skip to content

467. Unique Substrings in Wraparound String 👍

  • Time: $O(n)$
  • Space: $O(26)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int findSubstringInWraproundString(string s) {
    int maxLength = 1;
    // count[i] := the number of substrings ending in ('a' + i)
    vector<int> count(26);

    for (int i = 0; i < s.length(); ++i) {
      if (i > 0 && (s[i] - s[i - 1] == 1 || s[i - 1] - s[i] == 25))
        ++maxLength;
      else
        maxLength = 1;
      const int index = s[i] - 'a';
      count[index] = max(count[index], maxLength);
    }

    return accumulate(count.begin(), count.end(), 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int findSubstringInWraproundString(String s) {
    int maxLength = 1;
    // count[i] := the number of substrings ending in ('a' + i)
    int[] count = new int[26];

    for (int i = 0; i < s.length(); ++i) {
      if (i > 0 && (s.charAt(i) - s.charAt(i - 1) == 1 || s.charAt(i - 1) - s.charAt(i) == 25))
        ++maxLength;
      else
        maxLength = 1;
      final int index = s.charAt(i) - 'a';
      count[index] = Math.max(count[index], maxLength);
    }

    return Arrays.stream(count).sum();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def findSubstringInWraproundString(self, s: str) -> int:
    maxLength = 1
    # count[i] := the number of substrings ending in ('a' + i)
    count = [0] * 26

    for i in range(len(s)):
      if i > 0 and (ord(s[i]) - ord(s[i - 1]) == 1
                    or ord(s[i - 1]) - ord(s[i]) == 25):
        maxLength += 1
      else:
        maxLength = 1
      index = ord(s[i]) - ord('a')
      count[index] = max(count[index], maxLength)

    return sum(count)