1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

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

string LongestCommonPrefix(vector<string> &strs) 
{
    if (strs.size() <= 0)return "";
    if (strs.size() == 1)return strs[0];

    string result = "";

    for (int i = 0; i < strs[0].size(); ++i)
    {
        const char c = strs[0][i];
        for (int j = 1; j < strs.size(); ++j)
            if (strs[j].size() <= i || c != strs[j][i])
                return result;

		result.push_back(c);
    }

    return result;
}


int main(int argc, char** argv)
{
    vector<string> strs;

    strs.push_back("abcabc");
    strs.push_back("abca");
    strs.push_back("abc");
    strs.push_back("abcb");

    cout << LongestCommonPrefix(strs);
    return 0;
}
View Program Text


Test Status