LeetCode题解:Longest Common Prefix

Longest Common Prefix

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

思路:

两个字符串的LCP可以通过依次比较相应字符的方法来完成。

题解:

class Solution {
public:
    string lcp(const string& s1, const string& s2)
    {
        const int L1 = s1.size();
        const int L2 = s2.size();
        
        string LCP;
        for(int i = 0; i < min(L1, L2); ++i)
        {
            if (s1[i] == s2[i])
                LCP += s1[i];
            else
                break;
        }
        
        return LCP;
    }

    string longestCommonPrefix(vector<string> &strs) {
        if (strs.size() == 0)
            return string("");
            
        string LCP = strs[0];
        for(auto& s : strs)
            LCP = lcp(s, LCP);
        
        return LCP;
    }
};


你可能感兴趣的:(LeetCode)