-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcountSubstringsWithRepeatingCharacter.js
More file actions
51 lines (40 loc) · 1.21 KB
/
countSubstringsWithRepeatingCharacter.js
File metadata and controls
51 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @param {string} s
* @return {number}
*/
/*
https://leetcode.com/problems/count-substrings-without-repeating-character/description/
- Hunting phase
- right pointer moves forward as long as we have not encountered duplicates
- Catchup phase
- left pointer moves forward until the substring contained by the range is
special
*/
var numberOfSpecialSubstrings = function(s) {
let result = 0;
let encountered = new Set();
let left = 0;
let right = 0;
while (right < s.length) {
// hunting phase
while (right < s.length && !encountered.has(s[right])) {
encountered.add(s[right]);
right++;
}
// catchup phase
if (right >= s.length) {
break;
}
// calculate previous special substring combos
let priorRangeLength = right - left;
result += (priorRangeLength * (priorRangeLength + 1) / 2);
while (encountered.has(s[right])) {
encountered.delete(s[left]);
left++;
}
}
let priorRangeLength = right - left;
result += (priorRangeLength * (priorRangeLength + 1) / 2);
return result;
};
// console.log(numberOfSpecialSubstrings('abca'));