We are required to write a JavaScript function that takes in a string. The function should find and return the length of the longest substring that is sandwiched between two same letters.
For example −
If the input string is −
const str = 'avbghvh';
Then the output should be −
const output = 3;
because the desired longest substring is 'bgh' between two v's.
Example
const str = 'avbghvh';
const longestSub = (str = '') => {
const map = new Map();
let max = -1;
for(let i = 0; i < str.length; i++){
if(map.has(str.charAt(i))){
max = Math.max(max, i - map.get(str.charAt(i)) - 1);
}else{
map.set(str.charAt(i), i);
};
};
return max;
};
console.log(longestSub(str));Output
This will produce the following output −
3