Topic:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string"".
Example:
Input: ["flower","flow","flight"]
Output: "fl"
Example2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Answer:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0) return "";
if(strs.size()==1) return strs[0];
int minimum=strs[0].size();
int growing_length=0;
for(string s:strs){
if(s.size()<minimum)
minimum=s.size();
}
for(int j=0;j<minimum;j++){
int judge=1;
for(int i=1;i<strs.size();i++){
if(strs[0].at(j)!=strs[i].at(j)){
judge=0;
}
}
if(judge==0&&j==0)
return "";
if(judge==1)
growing_length++;
}
if(growing_length==0)
return "";
else
return strs[0].substr(0,growing_length);
}
};