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

最长公共前缀 #5

Open
Bulandent opened this issue Jan 5, 2021 · 0 comments
Open

最长公共前缀 #5

Bulandent opened this issue Jan 5, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

最长公共前缀

难度:简单
来源:LeetCode 14

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

示例 1:

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

示例 2:

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

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

思路:
如果数组长度为1,则返回数组第一项

题解:

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    if (strs && strs.length === 0) return ''
    if (strs.length === 1) return strs[0]
    
    let pre = strs[0]
    for (let i = 1, l = strs.length; i < l; i++) {
        let j = 0
        for (; j < pre.length && j < strs[i].length; j++) {
            if (pre[j] !== strs[i][j]) {
                break
            }
        }
        pre = pre.substring(0, j)
    }
    return pre
};
  • 时间复杂度:最坏 ,s 为所有字符串的长度之和;执行用时:88 ms
  • 空间复杂度:;内存消耗:38.2 MB
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