LeetCode【#14】 Longest Common Prefix

题目链接:

点击跳转

 

题目:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

题目分析:

给定一个字符串数组,求最大公共前缀。

 

解题思路:

一开始的思路,先给字符串数组排序,然后利用最小的那个(长度也肯定是最小)来依次遍历所有字符串的从0到 最小长度-1。如果只要出现不等的,直接就返回值结束函数。

这种情况下的复杂度是 O(n*m)与排序复杂度中的最大值,其中n是字符串的个数,m是字符串中长度最小的长度。

上面是思路一。

然后接着考虑有没有更好的,即思路二:

我们进行排序之后,有出现一个最小值和最大值,那么我们是不是只用比较这个最大值和最小值的公共前缀就可以了,因为其他字典序是在两者之间,如果中间已经出现不同了,那么最小的和最大的也就不同。

所以这种情况下的复杂度主要就是排序的复杂度。

(从最后的运行结果来看,运行时间一样,所以主要影响是排序的复杂度,主要原因是可能思路一其实不用排序也是可以解决的)

 

AC代码:

思路一:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int len = strs.size();
        if(len == 0)
            return "";
        string res = "";
        sort(strs.begin(),strs.end());
        int minLen = strs[0].size();
        for(int i = 0;i < minLen;i++)
        {
            for(int j = 1;j < len;j++)
            {
                if(strs[j][i] != strs[j-1][i])
                    return res;
            }
            res += strs[0][i];
        }
        return res;
    }
};

运行结果:

Runtime: 8 ms, faster than 94.25% of C++ online submissions for Longest Common Prefix.

Memory Usage: 9.1 MB, less than 61.58% of C++ online submissions for Longest Common Prefix.

思路二:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int len = strs.size();
        if(len == 0)
            return "";
        string res = "";
        sort(strs.begin(),strs.end());
        string s1 = strs[0];
        string s2 = strs[len-1];
        int minLen = strs[0].size();
        for(int i = 0;i < minLen;i++)
        {
            if(s1[i] != s2[i])
                return res;
            res += s1[i];
        }
        return res;
    }
};

运行结果:

Runtime: 8 ms, faster than 94.25% of C++ online submissions for Longest Common Prefix.

Memory Usage: 8.9 MB, less than 71.71% of C++ online submissions for Longest Common Prefix.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值