First let us figure out what should i do,we need find the common prefix for all strings in the vector
So we just need compare the char in the same position for each string
But how to denote the particular char in the particular string in a vector?
Let us use the example 1 for a explanation
So if we wanna denote the 'r' in the 'flower' ,we can use strs[0][5] to refer 'r'
So now we get the methods to make a comparison for each char,if it is the same we save it into the result string
but we also need to notice if it exit in the position of a string
We use the code to check :if(strs[j][i]=='\0')
so the full code is:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
//first we define a string for storing the result
string commonprefix="";
int condition=1;
for(int i=0;i<strs[0].size();i++){
char currentchar=strs[0][i];
for(int j=1;j<strs.size();j++)
{
//should require two conditions :the position of the string is not NULL and same with currentchar,here we use the contrary condition for understand easily.
if(strs[j][i]=='\0'||strs[j][i]!=currentchar){
return commonprefix;
}
}
commonprefix.push_back(currentchar);
}
return commonprefix;
}
};
Thank you for reading!
Top comments (0)