Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Substring dài nhất giữa hai ký tự giống nhau trong JavaScript

Viết hàm tìm độ dài substring dài nhất bị kẹp giữa hai ký tự giống nhau trong chuỗi.

Ví dụ: 'sadtrsewak' → 6 (giữa hai 'a' có 'dtrsew').

Ví dụ

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(el)) {
      res = Math.max(res, i - map[el] - 1);
    } else {
      map[el] = i;
    }
  }
  return res;
};
console.log(longestSubstringBetween(str));

Kết quả

6