Strings - Longest Common Prefix

Strings - Longest Common Prefix

Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/description/

My approach:

  1. I sorted the array in the ascending order of the string sizes.

  2. Then I checked every character of the arr[0] with others strings.

  3. If they all have that character then I'll add it to my 'ans'.

  4. The moment they don't match I'll return the ans (initiliaze ans = "").

Code:

Using Sorting:

bool comp(string a, string b){
    return a.size()<b.size();
}

class Solution {
public:

    string longestCommonPrefix(vector<string>& arr) {

        sort(arr.begin(), arr.end(), comp);

        string ans = "";

        int n = arr.size();
        int m = arr[0].size();

        for(int i=0;i<m;i++){
            char ch = arr[0][i];

            for(int j=1;j<n;j++){
                if(arr[j][i]!=ch){
                    return ans;
                }
            }

            ans += ch;
        }
        return ans;
    }
};