본문 바로가기
Coding Test/LeetCode

[Javascript] (LeetCode) 28. Implement strStr() (Easy)

by Chaedie 2022. 8. 3.
728x90

[Javascript] (LeetCode) 28. Implement strStr() (Easy)

💡 구글에 Javascript 풀이가 많이 없거나, 배운 점이 있으면 포스팅합니다.

내 풀이 (메서드 없이)

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  let matchCount = 0;
  let j = 0;
  for (let i = 0; i < haystack.length; i++) {
    if (haystack[i] === needle[j]) {
      for (let j = 0; j < needle.length; j++) {
        if (haystack[i + j] === needle[j]) {
          matchCount++;
          if (matchCount === needle.length) {
            return i;
          }
        } else {
          matchCount = 0;
          break;
        }
      }
    }
  }
  return -1;
};
  • 함수 분리 풀이 (뎁스가 너무 깊어서)
var strStr = function(haystack, needle) {
  for (let i = 0; i < haystack.length; i++) {
    if (haystack[i] === needle[0]) {
      let returnValue = findNeedleFromI(haystack, needle, i);
      if ( returnValue !== -1) {
        return returnValue;
      }
    }
  }
  return -1;
};

function findNeedleFromI(haystack, needle, i) {
  let matchCount = 0;
  for (let j = 0; j < needle.length; j++) {
    if (haystack[i + j] === needle[j]) {
      matchCount++;
      if (matchCount === needle.length) {
        return i;
      }
    } else {
      matchCount = 0;
      break;
    }
  }

  return -1;
}
  • 뎁스가 깊어서 함수 분리해서 풀어보았습니다.
  • 근데 속도는 조금 더 느려지네요. 좋은 풀이를 찾아보고 싶습니다.

내장 함수 (치트키) 사용 ㅋㅋ

var strStr = function(haystack, needle) {
  return haystack.indexOf(needle);
};

배운 점, 느낀 점

  • 내장 함수가 속도면에서 꿀입니다…

댓글