One simple solution for leetcode problem 14

hallowaw

hallowaw

Posted on June 24, 2024

One simple solution for leetcode problem 14

Image description

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;
    }
};
Enter fullscreen mode Exit fullscreen mode

Thank you for reading!

💖 💪 🙅 🚩
hallowaw
hallowaw

Posted on June 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

while, do-while and for loops in C++
beginners while, do-while and for loops in C++

March 7, 2024

If statements in C++
beginners If statements in C++

March 4, 2024

Operators and true folse .
beginners Operators and true folse .

March 14, 2023