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

第十四题 - 最长公共前缀 #15

Open
laizimo opened this issue May 28, 2020 · 0 comments
Open

第十四题 - 最长公共前缀 #15

laizimo opened this issue May 28, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 28, 2020

题目描述

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

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

示例 1:
输入: ["flower","flow","flight"]
输出: "fl"

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

说明:
所有输入只包含小写字母 a-z 。

算法

单指针法

答案

/**
 * 单指针法
 */
var longestCommonPrefix = function(strs) {
    //#1 判断输入是否为空
    if (!strs.length) return "";
    //#2 取第一个字符串
    let i = 0;
    let tempS = strs[0];
    //#3 遍历第一个字符串
    for (; i < tempS.length; i++) {
        //#4 取出下标对应的字符
        let chat = tempS[i];
        let isExist = true;
        //#5 判断每个字符串的下标字符是否一致
        for (let j = 1; j < strs.length; j++) {
            if (strs[j][i] !== chat) {
                isExist = false;
                break;
            }
        }
        //#6 判断不一致 返回
        if (!isExist) break;
    }
    return tempS.slice(0, i);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant