Longest Common Prefix

C++

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Solution
{
  public:
    string longestCommonPrefix(vector<string> &strs)
    {
        if (strs.size() == 0)
            return "";
        string result = strs[0];
        for (int i = 0; i < strs[0].length(); i++)
        {
            for (int j = 1; j < strs.size(); j++)
            {
                if (i == strs[j].length() || strs[j][i] != strs[0][i])
                    return strs[0].substr(0, i);
            }
        }
        return strs[0];
    }
};

int main()
{
    Solution *s = new Solution();
    vector<string> vec;
    vec.push_back("leetcode");
    vec.push_back("leedcode");
    vec.push_back("leetcodes");
    cout << s->longestCommonPrefix(vec) << endl;
    system("pause");
    return 0;
}

Java

Sort the array first, and then you can simply compare the first and last elements in the sorted array.

python

Last updated

Was this helpful?