0 0
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);
        }
    }
};
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *