原题:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
普通的字符串处理题,可以直接通过逐位的循环来检测;可以通过先找出最短字符串的预处理来优化匹配过程。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(!strs.size())
return "";
int minLen = INT_MAX;
string _std;
for(int i(0); i < strs.size(); i++)
{
if(minLen > strs[i].length())
{
_std = strs[i];
minLen = strs[i].length();
}
}
bool flag = 1;
int pos;
for(pos = 0; pos < _std.length(); pos++)
{
for(int j(0); j < strs.size(); j++)
{
if(_std[pos] != strs[j][pos])
{
flag = 0;
break;
}
}
if(!flag)
{
pos --;
break;
}
}
string ans = "";
for(int i(0); i <= pos; i++)
ans += _std[i];
return ans;
}
};