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

14.最长公共前缀 #33

Open
wind-jyf opened this issue Apr 21, 2020 · 0 comments
Open

14.最长公共前缀 #33

wind-jyf opened this issue Apr 21, 2020 · 0 comments
Labels

Comments

@wind-jyf
Copy link
Owner

最长公共前缀

一、题目说明

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

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

示例 1:

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

示例 2:

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

说明:

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

二、解题思路

此题可以采用二维数组的方式,以数组中的第一个字符串为基准,依次对其他字符串的每一个字符与第一个字符串的每一个字符进行比较。

  1. 遍历第一个字符串的每一个字符
  2. 遍历的同时对其他字符串同样下标的字符进行比较
  3. 如果发现不相同,则直接返回
  4. 如果相同,就将当前比较的字符进行相加记录

三、代码实现

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    if(!strs.length){
        return ''
    }
    let str = '';//记录公共子串
    for(let i =0;i<strs[0].length;i++){
        for(let j =1;j<strs.length;j++){
            if(strs[0][i]!=strs[j][i]){
                return str;
            }
        }
        str+=strs[0][i];
    }
    return str;
};

参考


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