LC 14. Longest Common Prefix

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        if(n==0){
            return "";
        }
        string s[n+1];
        int len[n+1];
        for(int i=0;i<n;i++){
            s[i] = strs[i];
            len[i] = s[i].size();
        }
        sort(len, len+n);
        int ln = len[0];
        int mx = ln;
        for(int i = 1 ;i < n ;i++){
            for(int j = 0;j<ln;j++){
                if(s[0][j] == s[i][j]){
                    continue;
                }
                else{
                    if(j < mx){ 
                        mx = j;
                    }
                    break;
                }
            }
        }
        if(mx == 0){
            return "";
        }
        char str[ln + 1];
        for(int i =0;i<mx ;i++){
            str[i] = s[0][i];
        }
        str[mx] = '\0';
        return str;
        
    }
};


Dicussion Forum