leetcode --- js版本程序员

leetcode-Easy-第4期-longest common

2019-02-27  本文已影响2人  石头说钱

求数组中各元素的最长的公共前缀

Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

解法

var longestCommonPrefix = function(strs) {
  if (strs.length === 0) return '';
  return strs.reduce((result, s) => {
      return longestInTwo(result, s);
  });
};
const longestInTwo = (a, b) => {
  let long, short;
  if (a.length > b.length) {
      long = a;
      short = b;
  } else {
      long = b;
      short = a;
  }
  while (long.indexOf(short) !== 0) {
      short = short.slice(0, -1);
  }
  return short;
};

上一篇 下一篇

猜你喜欢

热点阅读