leetcode 题解 || Longest Common Prefix 问题

problem:

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

寻找 0 ~n 个字符串的最长公共前缀


thinking:

(1)公共前缀非常好理解。按位匹配就可以

(2)非常easy忘记处理0、1个字符串的情况。


code:

string prefix(string &str1, string &str2)
{
    string tmp;
    int i=0;
    while((i<str1.size())&&(i<str2.size())&&(str1.at(i)==str2.at(i)))
    {
        tmp.push_back(str1.at(i));
        i++;
    }
    return tmp;
}
class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.size()==0)
            return "";
        if(strs.size()==1)
            return strs.at(0);
        string result=prefix(strs.at(0),strs.at(1));
        for(int i=1;i<strs.size();i++)
        {
            result=prefix(strs.at(i),result);
        }
        
        return result;
    }
};


原文地址:https://www.cnblogs.com/liguangsunls/p/6920341.html