美文网首页
最长公共前缀

最长公共前缀

作者: 灯火葳蕤234 | 来源:发表于2019-03-06 19:48 被阅读0次

Write a function to find the longest common prefix string amongst an array of
If there is no common prefix, return an empty string "".
编写一个函数来查找字符串数组中最长的公共前缀字符串。
如果没有公共前缀,则返回空字符串“”。

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) {
    var len = strs.length;
    if(strs.length == 0){
        console.log(strs.length)
        return ""
    }else{
        console.log(strs.length)
        var minLen = strs[0].length;
        var count = 0;
        for(let i = 1;i < len;i++){
            if(strs[i].length < minLen){
                minLen = strs[i].length;
            }
        }
        for(let j = 1;j <= minLen;j++){
            let leep = true;
            for(let i = 0;i < len;i++){
                if(strs[i].indexOf(strs[0].slice(0,j)) != 0){
                    leep = false;
                }
            }
            if(leep == true){
                count++;
            }else{
                return strs[0].slice(0,count);
            }
        }
        return strs[0].slice(0,count);
    }
};

相关文章

  • LeetCode 每日一题 [19] 最长公共前缀

    LeetCode 最长公共前缀 [简单] 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回...

  • 14. 最长公共前缀

    20180923-摘抄自14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,...

  • 5,最长公共前缀/数组与字符串

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

  • Swift 最长公共前缀 - LeetCode

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

  • leetcode探索之旅(14)

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

  • Leetcode 14 最长公共前缀

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

  • LeetCodeSwift 14.Longest Common

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

  • [day4] [LeetCode] [title14,122]

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

  • 14. 最长公共前缀

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

  • leetcode算法-最长公共前缀

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

网友评论

      本文标题:最长公共前缀

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