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. 最长公共前缀 #65

Open
funnycoderstar opened this issue Apr 13, 2020 · 0 comments
Open

14. 最长公共前缀 #65

funnycoderstar opened this issue Apr 13, 2020 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Apr 13, 2020

JavaScript实现Leetcode 14. 最长公共前缀

题目描述

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

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

示例 1:

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

示例 2:

输入: ["dog","racecar","car"]
输出: ""

解释: 输入不存在公共前缀。
说明:

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

解析思路

  1. 字符串数组长度为0时,公共前缀为空,直接返回
  2. 初始化公共前缀 commonPrefix 为 第一个字符串
  3. 遍历后面的字符串依次和 commonPrefix 进行比较,两两找出公共前缀,最终结果即为 最长公共前缀

解题方法

/**
 * @param {string[]} strs
 * @return {string}
 * 1. commonPrefix为 flower
 * 2. 比较 flower和flow,相同的值为 fl
 * 3. 比较 fl 和 flight,形同的值为 fl
 * 如何比较 flower和flow: c使用for循环,一个字符一个字符的比较
 */
var longestCommonPrefix = function(strs) {
    if(!strs.length) {
        return '';
    }
    let common = '';
    // 第一个字符串为初始值
    let commonPrefix = strs[0];
    for(let i = 0 ; i < commonPrefix.length; i++) {
        // 遍历strs中剩下的 的值
        for(let j = 1; j < strs.length; j++) {
            // 每一个都和 commonPrefix 比较,找到公共的部分,否则返回 common
            if(commonPrefix[i] !== strs[j][i]) {
                return common;
            }
        }
        common += commonPrefix[i];
    }
    return common;
};
  • 时间复杂度: O(n),n为所有字符串长度之和
  • 空间复杂度: O(1),使用常量来存储变量
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant