Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最长公共前缀 #39

Open
CodeRookie262 opened this issue Feb 22, 2021 · 1 comment
Open

最长公共前缀 #39

CodeRookie262 opened this issue Feb 22, 2021 · 1 comment
Labels

Comments

@CodeRookie262
Copy link
Owner

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成

来源:LeetCode

@CodeRookie262
Copy link
Owner Author

CodeRookie262 commented Feb 23, 2021

逐一项对比

var longestCommonPrefix = function(strs) {
    if(strs.length === 0) return '';
    var ans = strs[0]; // 默认第一项为最长前缀

    for(var i = 1;i < strs.length;i++){
        for(var j = 0;j < Math.max(ans.length, strs[i].length);j++){
            if(ans[j] !== strs[i][j]){
                ans = ans.slice(0,j);
                break;
            }
        }
    }
    return ans;
};

逐一字符串对比

var longestCommonPrefix = function(strs) {
    let ans = '';
    if(!strs.length) return ans;

    for(var i = 0;i < strs[0].length;i++){
        for(var j = 1;j < strs.length;j++){
            if(strs[0][i] !== strs[j][i]){
                return ans;
            }
        }
        ans += strs[0][i]
    }

    return ans;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant