HZFE / algorithms-solving

1 stars 0 forks source link

2022-08-19 #21

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

14 Longest Common Prefix

/*
 * @lc app=leetcode id=14 lang=typescript
 *
 * [14] Longest Common Prefix
 */

// @lc code=start
function longestCommonPrefix(strs: string[]): string {
    const num = Math.min(...strs.map(s => s.length));
    const common = [] as string[];

    for (let i = 0; i < num; i++) {
        const start = strs[0][i];
        if (strs.every(s => s[i] === start)) {
            common.push(start);
        } else {
            break;
        }
    }

    return common.join('');
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms

Akiq2016 commented 2 years ago
// @lc code=start
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
  if (strs.length === 1) return strs[0];

  const arr = strs.sort((a, b) => a.length - b.length);
  let res = arr[0];
  let i = res.length - 1;

  while (i >= 0) {
    for (j = 1; j < arr.length; j++) {
      if (!arr[j].startsWith(res)) {
        res = res.slice(0, i);
        i--;
        break;
      }
      if (j === arr.length - 1) {
        i = -1;
      }
    }
  }

  return res;
};
// @lc code=end