LeetCode Solutions

467. Unique Substrings in Wraparound String

Time: $O(n)$

Space: $O(26)$

			

class Solution {
 public:
  int findSubstringInWraproundString(string p) {
    int maxLength = 1;
    vector<int> count(26);  // Substrings end at i

    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(begin(count), end(count), 0);
  }
};
			

class Solution {
  public int findSubstringInWraproundString(String p) {
    int maxLength = 1;
    int[] count = new int[26]; // Substrings end at i

    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();
  }
}