-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestSubStringWithoutRepeat.ts
More file actions
105 lines (85 loc) · 2.32 KB
/
Copy pathlongestSubStringWithoutRepeat.ts
File metadata and controls
105 lines (85 loc) · 2.32 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
type RepeatCharacter = {
[c: string]: number;
};
/**
* Check if the string has unique sub string or not with the given length
* @param str - the string
* @param lengthOfSubString - length of subString
* @returns
*/
function isValidUniqueString(str: string, lengthOfSubString: number): boolean {
let valid = false;
const repeatedCharacter: RepeatCharacter = {};
let uniqueCharacters = 0;
for (let index = 0; index < str.length; index++) {
const character = str.charAt(index);
// If repeatedCharacter did not existed, created one
if (!repeatedCharacter[character]) {
repeatedCharacter[character] = 0;
}
repeatedCharacter[character]++;
if (repeatedCharacter[character] === 1) {
uniqueCharacters++;
}
if (index >= lengthOfSubString) {
repeatedCharacter[str.charAt(index - lengthOfSubString)]--;
if (repeatedCharacter[str.charAt(index - lengthOfSubString)] === 0) {
uniqueCharacters--;
}
}
if (index >= lengthOfSubString - 1 && uniqueCharacters === lengthOfSubString) {
valid = true;
}
}
return valid;
}
function lengthOfLongestSubstring(s: string): number {
let maxLength = 0;
let begin = 1;
let end = s.length;
let mid = 0;
while (begin <= end) {
mid = Math.floor((begin + end) / 2);
// Find the unique sub string length from the begin to end
if (isValidUniqueString(s, mid)) {
maxLength = mid;
begin = mid + 1;
} else {
end = mid - 1;
}
}
return maxLength;
}
// console.log(lengthOfLongestSubstring(' '));
/**
* Using siding window algorithm
* @param s
* @returns
*/
function lengthOfLongestSubstringV2(s: string): number {
if (s.length === 0) return 0;
if (s.length === 1) return 1;
const repeatedCharacter: RepeatCharacter = {};
let maxLength = 0;
let left = 0;
let right = 0;
while (right <= s.length - 1) {
if (repeatedCharacter[s.charAt(right)] === undefined) {
repeatedCharacter[s.charAt(right)] = 0;
}
if (repeatedCharacter[s.charAt(left)] === undefined) {
repeatedCharacter[s.charAt(left)] = 0;
}
if (repeatedCharacter[s.charAt(right)] === 1) {
while (repeatedCharacter[s.charAt(right)] === 1) {
repeatedCharacter[s.charAt(left)] = 0;
left++;
}
}
repeatedCharacter[s.charAt(right)] = 1;
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
console.log(lengthOfLongestSubstringV2('abcadac'));