class Solution {
//1. find out the minimum size string as the pivot string
//2. check every other string and update the minSize
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(strs.size() == 0) return string("");
int minSize = strs[0].size();
int pivotIdx = 0;
for(int i = 0; i < strs.size(); ++i)
if(strs[i].size() < minSize)
{
minSize = strs[i].size();
pivotIdx = i;
}
for(int i = 0; i < strs.size(); ++i)
{
if(i == pivotIdx) continue;
for(int j = 0; j < minSize; ++j)
{
if(strs[i][j] != strs[pivotIdx][j])
{
minSize = j;
break;
}
}
}
return strs[pivotIdx].substr(0, minSize);
}
};
second time
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(strs.size() == 0) return string("");
int strIdx = 0;
//choose the smallest string first
for(int i = 1; i < strs.size(); ++i)
if(strs[i].size() < strs[strIdx].size()) strIdx = i;
int commonLen = strs[strIdx].size();
for(int i = 0; i < strs.size(); ++i)
{
if(i == strIdx) continue;
int curLen = 0;
for(int j = 0; j < strs[i].size() && j < commonLen; ++j)
{
if(strs[strIdx][j] == strs[i][j]) curLen++;
else break;
}
commonLen = curLen;
}
return strs[strIdx].substr(0, commonLen);
}
};
本文介绍了一种寻找字符串数组中最长公共前缀的有效算法。通过选取最短字符串作为基准,逐个字符比较来确定所有字符串的公共部分。该方法简单且高效,适用于多种编程任务。
305

被折叠的 条评论
为什么被折叠?



