[#002] 28. Implement strStr()


Posted by s1101192101 on 2021-05-12

  • link:
    leetcode

  • 解題思路:

    1. 使用雙層迴圈對 haystack 及 needle 做比對
    2. 若比對到不符合的字原則跳出迴圈

  • 程式碼:

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
const strStr = function(haystack, needle) {
  if ((haystack.length === 0 && needle.length === 0) || haystack === needle) {
    return 0;
  }

  let isMatch;
  for (var i = 0; i < haystack.length - needle.length + 1; i++) {
    isMatch = true;
    for (var j = 0; j < needle.length; j++) {
      if (haystack[i + j] !== needle[j]) {
        isMatch = false;
        break;
      }
    }
    if (isMatch) break;
  }

  return isMatch ? i : -1;
};


  • 結果:



#Leetcode #string #easy







Related Posts

【Day04】用 you-get 測試下載 Youtube 影片

【Day04】用 you-get 測試下載 Youtube 影片

[ java ] JDBC 連線

[ java ] JDBC 連線

[ Nuxt.js 2.x 系列文章 ] VueX Store 搭配 vuex-persistedstate 狀態保存工具

[ Nuxt.js 2.x 系列文章 ] VueX Store 搭配 vuex-persistedstate 狀態保存工具


Comments