0% completed
I would like add two point. 1. The while loop is not necessary, because we are ...
Viacheslav Lushchinskiy
Oct 25, 2022
I would like add two point.
- The while loop is not necessary, because we are asked for longest substring, so we do not have to waist CPU to shrink the string or array in the next task on more than 1 element. So if statement with just one iteration is enough
- In JS you can make use of Set data structure, that is more elegant as HashMap.
const func = (_str, _k) => { let result = []; let windowStart = 0; let setUnique = new Set() // Set keeps only uniq elements
for (let windowEnd = 0; windowEnd < _str.length; windowEnd++) { const _arr = [..._str] // transform string to array result.push(_arr[windowEnd]) setUnique.add(_arr[windowEnd])
if (setUnique.size > _k) { result.shift(); setUnique.delete(_arr[windowStart]) windowStart += 1; } } return result.length; };
0
0
Comments
Design Gurus3 years ago
You code will fail for the following input:
"pbpmmm" 2
You code will output '5', whereas the correct answer is '4'.
Viacheslav Lushchinskiy3 years ago
yes, true. So I need to wrap Set.delete in "if" statement like this if ( !result.includes(_arr[windowStart])) { setUnique.delete(_arr[windowStart]) } This makes it now similar to the logic HashMap but the question may be raised about the complexity of "includes" method...
Design Gurus3 years ago
You would need a 'while' loop.
Please share your complete solution with HashMap and we will try to explain.
Viacheslav Lushchinskiy3 years ago
I will post it as a new message for better visibility
On this page