Simple Implementation in C++


#1

string Solution::longestCommonPrefix(vector<string> &A) {
    int n = A.size();
    
    if(n == 1){
        return A[0];
    }
    
    string ans = "";
    
    int min_len = A[0].size();
    for(int i = 1; i < n; i++){
        if(A[i].size() < min_len) {
            min_len = A[i].size();
        }
    }
    
    for(int i = 0; i < min_len; i++){
        for(int j = 1; j < n; j++){
            if(A[j][i] == A[j-1][i]) {
                if(j == 1){
                    ans += A[j-1][i];
                }
            } else {
                return ans.substr(0, i);
            }
        }
    }
    
    return ans;
}