Sunny-117/js-challenges

最长重复子串

Pcjmy opened this issue · 2 comments

Pcjmy commented
最长重复子串

for循环大法

function getLongestRepeatString(s) {
    if (!s) return s;
    let ans = '';
    const map = new Set();
    for (let i = 0; i < s.length; i++) {
        for (let j = i + 1; j <= s.length; j++) {
            const chs = s.substring(i, j);
            if (map.has(chs) && chs.length > ans.length) {
                ans = chs;
            }

            map.add(chs);
        }
    }
    return ans;
}

console.log('abcbcabc =>', getLongestRepeatString('abcbcabc'));
//  abcbcabc => abc
console.log('abcabcacbd =>', getLongestRepeatString('abcabcacbd'));
//   abcabcacbd => abca
function getMaxLengthChdStr (str) {
  let right = 0
  let left = 0
  const set = new Set()
  while (right < str.length) {
    if (set.has(str[right])) {
      set.delete(str[right])
      left++
    } else {
      set.add(str[right])
      right++
    }
  }
  return right - left
}

console.log(getMaxLengthChdStr('abcdaccc'))