가장 짧은 문자거리

WooBuntu·2021년 2월 17일
0

JS 90제

목록 보기
10/33
  • 강의 듣기 전 내 풀이
const solution = (s, t) =>
  s.split('').map((char, index) => {
    const leftIndex =
      s.lastIndexOf(t, index) == -1
        ? Number.MAX_SAFE_INTEGER
        : Math.abs(s.lastIndexOf(t, index) - index);
    const rightIndex =
      s.indexOf(t, index) == -1
        ? Number.MAX_SAFE_INTEGER
        : s.indexOf(t, index) - index;
    return Math.min(leftIndex, rightIndex);
  });
// 시간복잡도가 n의 2승

const result = solution('teachermode', 'e');
console.log(result);
  • 강의를 반영한 풀이
const solution = (s, t) => {
  let standard = s.length;
  return (
    s
      .split('')
      .map((char, index) => {
        if (index == s.length - 1) standard = s.length;
        return char == t
          ? { char, distance: (standard = 0) }
          : { char, distance: ++standard };
      })
      // 각 문자에서 왼쪽에 있는 t까지의 거리
      .reverse()
      .map(({ char, distance }) =>
        char == t
          ? Math.min(distance, (standard = 0))
          : Math.min(distance, ++standard),
      )
      // 각 문자에서 오른쪽에 있는 t까지의 거리를 구한 뒤 왼쪽 거리와 비교하여 최소값 할당
      .reverse()
  );
};
// 시간 복잡도도 n일 뿐더러, 훨씬 똑똑한 방법인 것 같음

const result = solution('teachermode', 'e');
console.log(result);

0개의 댓글