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 p) {
    int maxLength = 1;
    // count[i] := the number of substrings ending in ('a' + i)
    vector<int> count(26);

    for (int i = 0; i < p.length(); ++i) {
      if (i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25))
        ++maxLength;
      else
        maxLength = 1;
      const int index = p[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 p) {
    int maxLength = 1;
    // count[i] := the number of substrings ending in ('a' + i)
    int[] count = new int[26];

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

    return Arrays.stream(count).sum();
  }
}