[#001] 14. Longest Common Prefix


Posted by s1101192101 on 2021-05-12

  • link:
    leetcode

  • 題目:


    编写一个函数来查找字符串数组中的最长公共前缀。
    如果不存在公共前缀,返回空字符串 ""。

  • 解題思路:

    1. 取得字串陣列中的最小字串長度
    2. 依照最小字串長度去逐一檢查 strs 中的字串
    3. strs[0] 為主要比較條件,若檢查不通過(strs[0][i] !== str[n][i])則跳出迴圈
    4. 若檢查通過則累加字元到變數中,並進行下一個字元的檢查(i++)
    5. 回傳累加字元的變數

  • 程式碼:

/**
 * @param {string[]} strs
 * @return {string}
 */
const longestCommonPrefix = function(strs) {
  let res = '';

  for (i = 0; i < getMinStrsLength(strs); i++) {
    if (!isStrsSameCharAtPoint(strs, i)) {
      break;
    }
    res += strs[0][i];
  }

  return res;
};

const getMinStrsLength = function(strs) {
  let res = Number.POSITIVE_INFINITY;
  strs.forEach(function(str) {
    res = str.length < res ? str.length : res;
  });

  return res;
};

const isStrsSameCharAtPoint = function(strs, point) {
  let res = true;
  strs.forEach(function(str) {
    if (strs[0][point] !== str[point]) {
      res = false;
      return false;
    }
  });

  return res;
};


  • 結果:



#Leetcode #string #easy







Related Posts

To Infinity and Beyond - Regression Kink Design

To Infinity and Beyond - Regression Kink Design

MTR04_0806

MTR04_0806

TypeScript 筆記:void 與 any

TypeScript 筆記:void 與 any


Comments