算法6:返回一组字符串的最长公共前缀

26 篇文章 0 订阅

问题描述

返回一组字符串的最长公共前缀,如 “abc”, “abcdef”, “abcd”, 则返回”abc”。

解题思路

首先最长公共前缀肯定小于或者等于最短字符串,设第一个字符串为公共字符串,公共字符串长度为第一个字符串的长度,遍历其他公共字符串,如果其他公共字符串比第一个字符串短,则公共字符串取较短的长度,如果其他字符串的字符不等于第一个字符串的字符,则退出比较,从而得当当前结果的公共字符串,以此类推,直至遍历除第一个字符串的其他字符串。

c++代码

string GetCommonPrefix(vector<string>& strs)
{
    string commonStr = "";
    int commonStrLen = 0;

    if(strs.size() <= 1)
    {
        return ""; 
    }

    //设第一个字符串就是公共字符串
    commonStr = strs[0];
    commonStrLen = commonStr.length();

    for (int i = 1; i < strs.size(); i++)
    {
        if(commonStrLen > strs[i].length())
        {
            commonStrLen = strs[i].length();
        }

        for(int j = 0; j < commonStrLen; j++)
        {
            if(commonStr[j] != strs[i][j])
            {
                commonStrLen = j;
                break;
            }
        }

        commonStr = strs[i].substr(0,commonStrLen);
    }

    return commonStr;
}

测试代码

int _tmain(int argc, _TCHAR* argv[])
{
    vector<string> strs;
    strs.clear();

    cout<<"please input 6 string:"<<endl;
    string temp;
    for(int i = 0; i < 6; i++)
    {
        cin>>temp;
        strs.push_back(temp);
    }

    string commonStr = GetCommonPrefix(strs);

    cout<<"common prefix string is "<<commonStr<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值