Write a function to find the longest common prefix string amongst an array of strings.
找出一组给定字符串的最长共同前缀。
这个最长共同前缀不是指两个字符串之间的,而是指所有字符串的最长共同前缀,例如给定str1 = "abcd" , str2 = "abc" , str3 = "ab" , str4 = "a" ,那么这4组字符串的最长共同前缀应该是"a",而不是str1与str2的"abc"。
我的思路是先找出最短字符串的长度,然后再在这个长度里面按顺序比较所有字符串的每一个字符即可。
另外,我特么又忘记给定字符串为空的情况了。。。以后在测试代码的时候一定先什么都不填就提交一次。。。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
if(strs.size()==0) return ans;
int min_length=strs[0].length();
for(int i=1;i<strs.size();i++)
if(strs[i].length()<min_length)
min_length=strs[i].length();
int count=0;
while(count<min_length)
{
int i=0;
for(;i<strs.size();i++)
if(strs[i][count]!=strs[0][count])
break;
if(i!=strs.size()) break;
count++;
}
ans=strs[0].substr(0,count);
return ans;
}
};