Longest Common Prefix

Problem:

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

Solution 1:My Solution

算法思路:

1.写一个求取两个字符串前缀的函数

2.遍历vector数组,依次求出前缀

时间复杂度分析:O(M*N)

    string commonPrefix(string str1, string str2)
    {
        int len1 = str1.length();
        int len2 = str2.length();
        if(0 == len1 || 0 == len2)
            return "";
        if(len1 > len2)
        {
            string temp = str1;
            str1 = str2;
            str2 = temp;
        }
        int index = len1 - 1;
        while(index >= 0)
        {
            str1 = str1.substr(0, index + 1);
            if(str2.find(str1) == 0)
                return str1;
            index --;
        }
        if(index < 0)
            return "";
        else return str1;
    }
    string longestCommonPrefix(vector<string> &strs) 
    {
        if(strs.size() == 0)
            return "";
        vector<string>::iterator it = strs.begin();
        string current = *it++;
        for(;it != strs.end(); it++)
        {
            current = commonPrefix(current, *it);
        }
        return current;
    }

Solution 2:转自网友

算法思路:

My idea is firstly sort array, then compare the first string with the last string. Time complexity is O(mnlog(n)) with m be average length of string. Although by advancing a counter and checking if every string[counter] is the same can achieve O(mn) time complexity, my solution solve the problem from an different angle, FYI.

时间复杂度分析:O(M*N*log(N))

string longestCommonPrefix(vector<string> &strs) {
    sort(strs.begin(),strs.end());
    int n = strs.size();
    if (n == 0) return "";
    if (n == 1) return strs[0];
    int length = 0;
    while (length < strs[0].size() && length < strs[n - 1].size() && strs[0][length] == strs[n - 1][length]) length++;
    return strs[0].substr(0,length);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值