leetcode 14 最长公共前缀

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


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

string longestCommonPrefix(const string& str1, const string& str2) {
int length = min(str1.size(), str2.size());
int index = 0;
while (index < length && str1[index] == str2[index]) {
++index;
}
return str1.substr(0, index);
}
};


class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return string();
sort(strs.begin(), strs.end());
string st = strs.front(), en = strs.back();
int i, num = min(st.size(), en.size());
for(i = 0; i < num && st[i] == en[i]; i ++);
return string(st, 0, i);
}
};


08-31 183

08-16 4350
09-12 228
04-30 616
05-04 118
10-17 153
04-25 522
08-02 360
08-01 4152
05-22 141
05-30 31
04-15 31
11-06 101
05-08 731
01-31 138
04-26 54