-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-2.js
65 lines (51 loc) · 1.91 KB
/
test-2.js
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
/*
Ejercicio #2:
Implemente una función que, dado un string s, encuentre la longitud del substring más largo que no repite caracteres.
Ejemplos:
Entrada: s = "abcabcbb"
Salida: 3
Explicación: El substring más largo que no repite letras es "abc", que tiene una longitud de 3. También hay otros de longitud 3 como "bca", "cab", entre otros. De longitud 4 no hay.
Entrada: s = "bbbbb"
Salida: 1
Explicación: El substring más largo que no repite letras es "b", que tiene una longitud de 1.
Entrada: s = "pwwkew"
Salida: 3
Explicación: El substring más largo que no repite letras es "wke", que tiene una longitud de 3. No hay substrings de longitud 4 que no repitan letras.
Por ejemplo, "pwke" no es un substring, dado que los caracteres no son seguidos.
*/
const findDuplicates = (arrayLetter) => {
let duplicates = [];
const tempArray = [...arrayLetter].sort();
for (let i = 0; i < tempArray.length; i++) {
if (tempArray[i + 1] === tempArray[i]) {
duplicates.push(tempArray[i]);
}
}
return duplicates.length > 0 ? true : false
}
const substringMaxLength = (s) => {
let arrayString = s.split('')
let actualMaxLength = 1
arrayString.forEach((element, index) => {
let subString = [element]
let countIndex = index + 1
let count = 1
if (index !== (arrayString.length - 1)) {
while ((arrayString[index] !== arrayString[countIndex]) && !findDuplicates(subString)) {
count++
subString.push(arrayString[countIndex])
countIndex++
}
}
actualMaxLength = actualMaxLength < count ? findDuplicates(subString) ? count - 1 : count : actualMaxLength
});
return actualMaxLength
}
const sample1 = 'abcabcbb';
const sample2 = 'bbbbb';
const sample3 = 'pwwkew';
const sample4 = 'yUIiUYrewq';
console.log(substringMaxLength(sample1));
console.log(substringMaxLength(sample2));
console.log(substringMaxLength(sample3));
console.log(substringMaxLength(sample4));