모든 아나그램 찾기

WooBuntu·2021년 2월 23일
0

JS 90제

목록 보기
20/33
  • 내 풀이
const solution = (s, t) => {
  let count = 0;
  const hashOfT = t
    .split('')
    .reduce(
      (hash, char) =>
        hash.hasOwnProperty(char)
          ? (hash[char]++, hash)
          : ((hash[char] = 1), hash),
      {},
    );
  const limit = s.length;
  const targetLength = t.length;
  let leftPointer = 0;
  const hashOfS = {};

  const compare = target => {
    for (const key in hashOfT) {
      if (target.hasOwnProperty(key)) {
        if ((target[key]--, target[key]) < 0) return false;
      } else return false;
    }
    return true;
  };

  for (let rightPointer = 0; rightPointer < limit; rightPointer++) {
    const char = s[rightPointer];
    hashOfS.hasOwnProperty(char) ? hashOfS[char]++ : (hashOfS[char] = 1);
    if (rightPointer >= targetLength) {
      const prevChar = s[leftPointer++];
      (hashOfS[prevChar]--, hashOfS[prevChar]) == 0 && delete hashOfS[prevChar];
    }
    if (rightPointer >= targetLength - 1 && compare({ ...hashOfS })) count++;
  }
  return count;
};

const result = solution('bacaAacba', 'abc');
console.log(result);

0개의 댓글