1
// One Pass Counting Solution
2
// 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring.
3
// 2. counts to track the longest continuos subtring starting with current character.
4
// Time complexity: O(N)
5
// Space complexity: O(1)
6
class Solution {
7
public int findSubstringInWraproundString(String p) {
8
final int N = p.length();
9
int res = 0, len = 1;
10
int[] counts = new int[26];
11
for (int i = 0; i < N; i++) {
12
char ch = p.charAt(i);
13
if (i > 0 && (ch - p.charAt(i - 1) == 1 || ch - p.charAt(i - 1) == -25)) {
14
len++;
15
} else {
16
len = 1;
17
}
18
int idx = ch - 'a';
19
counts[idx] = Math.max(counts[idx], len);
20
}
21
for (int count : counts) {
22
res += count;
23
}
24
return res;
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0