JavaScript 中兩個相同字元之間最大的子字串
我們需要編寫一個 JavaScript 函式,該函式只能獲取一個字串作為引數。
該函式應找到夾在兩個相同字元之間的最長字串並返回其長度。
例如 -
如果輸入字串為 -
const str = 'sadtrsewak';
那麼輸出應該為 -
const output = 6;
因為在兩個 ‘a’ 之間,我們有最長的期望子字串,長度為 6。
示例
程式碼如下 −
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));
輸出
控制檯輸出如下 -
6
廣告