Write a function to find the longest common prefix string amongst an array of strings.
这个题目非常简单,只要弄清楚题意就能够非常快地解决,我的C++代码实现以下:
string longestCommonPrefix(vector<string> &strs) {
if (strs.empty()) return "";
string commonPrefix = strs[0];
for (int i = 1; i < strs.size(); ++i) {
int j = 0;
for ( ; j < commonPrefix.size() && j < strs[i].size(); ++j) {
if (commonPrefix[j] != strs[i][j]) break;
}
commonPrefix = commonPrefix.substr(0, j);
}
return commonPrefix;
}
时间性能以下: