码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 14 Longest Common Prefix

时间:2015-04-25 19:48:20      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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

这题是寻找一组字符串的最长公共前缀,举个例子:

“abc” "a"显然lPrefixString = "a",注意检查空串的情况!!!

联系使用顺序程序,和递归解决以上问题:

 

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs)
{
    int nSize = strs.size();
    int nPrefixNum = INT_MAX;
    if(nSize  == 0)
    {
        return "";
    }
    string iCompare(strs[0]);
    for(int i= 0; i< nSize; ++i)
    {
        int temp = 0;
        
        if (iCompare.size() == 0 || strs[i].size() == 0)  
            return "";  

        string::size_type iScanA = 0;
        string::size_type iScanB = 0;
        while(iScanA != iCompare.size() && iScanB != strs[i].size() )
        {
            if(iCompare[iScanA] == strs[i][iScanB])
            {
                temp++;
                iScanA++;
                iScanB++;
            }
            else
            {
                break;
            }
        }
        if(temp < nPrefixNum )
        {
            nPrefixNum = temp;
            iCompare = strs[i];
        }
    }
    string ret;
    ret.assign(iCompare, 0, nPrefixNum);
    return ret;
}
};

 

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs)
{
    int nSize = strs.size();
    if(nSize == 0)
    {
        return "";
    }
    string iCompare(strs[0]);
    int nPrefix = INT_MAX;
    findlongestPrefix(strs, iCompare, 0, nPrefix);
    return iCompare.assign(iCompare, 0, nPrefix);
}
void findlongestPrefix(vector<string> &strs, string &src1, int i, int &nPrefixNum)
{
    string::size_type iScanA = 0;
    string::size_type iScanB = 0;
    int temp = 0;
    string src2(strs[i]);

    while(iScanA != src1.size() && iScanB != src2.size())
    {
        if(src1.size()==0 || src2.size()==0)
        {
            return ;
        }
        if(src1[iScanA] == src2[iScanB])
        {
            temp++;
            iScanA++;
            iScanB++;
        }
        else
        {
            break;
        }
    }
    int nSize = strs.size();
    if(i+1 == nSize)
    {
        if(temp < nPrefixNum)
            nPrefixNum = temp;
        return ;
    }
    if(temp < nPrefixNum)
    {   
        src1.assign(src1, 0, temp);
        nPrefixNum = temp;
        findlongestPrefix(strs, src1, i+1, nPrefixNum );
    }
    else
    {
        findlongestPrefix(strs, src1, i+1, nPrefixNum);
    }
    
    
}

};

一句话,你必须万分努力才能看起来毫不费力!

 

LeetCode 14 Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/bestwangjie/p/4456422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!