题目:找出n个字符串的最长公共前缀
需要注意字符串列表为空和字符串有空串的情况
c++:
string longestCommonPrefix(vector<string>& strs) {
sort(strs.begin(), strs.end());
if(strs.empty())
{
return "";
}
if(strs[0].empty())
{
return "";
}
string commonstr = strs[0];
string temp;
int begin = 0;
for(int i = 1; i < strs.size(); i++)
{
while(commonstr.at(begin) == strs[i].at(begin))
{
temp += commonstr.at(begin);
begin ++;
if(begin >= commonstr.length())
{
break;
}
}
if(temp.empty())
{
return "";
}
commonstr = temp;
temp = "";
begin = 0;
}
return commonstr;
}
Python:
先给字符串按照长度排序,然后从最小的串开始比较
def longestCommonPrefix(self, strs):
def ll(s):
return len(s)
if len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
strs.sort(key = ll)#按照字符串长度排序
if strs[0] == "":
return ""
begin = 0
common = strs[0]
for i in range(1, len(strs)):
while(common[begin] == strs[i][begin]):
begin += 1
if begin >= len(common):
break
common = common[:begin]
if begin == 0:
return ""
begin = 0
return common