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;
}
时间性能如下:
时间: 2024-10-13 10:58:51