Read Time:35 Second
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 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
C++
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int j=0;
char temp= strs[j][0];
bool endoffinding=false;
while(!endoffinding){
for(int i=0;i<strs.size();i++){
char current;
if(strs[i].length()>j){
current=strs[i][j];
}else {
endoffinding=true;
break;
}
if(current!=temp){
endoffinding=true;
break;
}
temp=current;
}
if(!endoffinding){
j++;
temp= strs[0][j];
}
}
if(j==0){
return "";
}else {
return strs[0].substr(0,j);
}
}
};