14. Longest Common Prefix | leetcode solution

 14Longest Common Prefix

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"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

solution:


class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
        string res1 ="";
        int length = INT_MAX;
        for(int i = 0 ; i < strs.size() ; i++)
        {
            if(strs[i].length() < length )
                length = strs[i].length();
        }
        for(int i = 0 ; i < length ; i++)
        {
            for(int j = 1 ; j < strs.size() ; j++ )
            {
                if(strs[j][i] != strs[j-1][i])
                    return res1;

            }
            res1 = res1 + strs[0][i];

        }
        return res1;
        
    }
};

Comments