美文网首页leetcode --- js版本程序员
leetcode-Easy-第4期-longest common

leetcode-Easy-第4期-longest common

作者: 石头说钱 | 来源:发表于2019-02-27 20:27 被阅读2次

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

    • Example 1:
    Input: ["flower","flow","flight"]
    Output: "fl"
    
    • Example 2:
    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;
    };
    
    

    相关文章

      网友评论

        本文标题:leetcode-Easy-第4期-longest common

        本文链接:https://www.haomeiwen.com/subject/qbrquqtx.html