Longest Common Prefix -最长公共前缀

问题:链接

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

解答:

注意 当传入參数为空,即vector<string> 大小为0时。应该直接返回一个空字符串“”。而不是返回NULL。

这点须要特别注意。


代码:

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.size() == 0)
            return "";
        int i = 0;
        char a;
        while(1)
        {
            if(i >= (*strs.begin()).size())
                return strs[0].substr(0,i);
            a = (*strs.begin())[i];
            for(vector<string>::iterator it = strs.begin()+1; it != strs.end(); ++it)
            {
                if(i >= (*it).size() || a != (*it)[i] )
                    return strs[0].substr(0,i);
            }
            ++i;
        }
    }
};


【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10670845.html