We are required to write a JavaScript function that takes in a string of characters as the only argument.
The function should find that longest string which is sandwiched between two identical characters and return its length.
For example −
If the input string is −
const str = 'sadtrsewak';
Then the output should be −
const output = 6;
because between two 'a' we have the longest desired substring of length 6.
Example
Following is the code −
const str = 'sadtrsewak'; const longestSubstringBetween = (str = '') => { const map = {}; let res = -1; for(let i = 0; i < str.length; i++){ const el = str[i]; if(map.hasOwnProperty(str[i])){ res = Math.max(res, i - map[el] - 1); }else{ map[el] = i; }; }; return res; } console.log(longestSubstringBetween(str));
Output
Following is the console output −
6