C++ | Simple | Easy to understand


#1

Prefix of first two elements, then for every subsequent element. In case of no match delete from that point till end in prefix.

string Solution::longestCommonPrefix(vector<string> &A) {
if(A.size() == 1) return A[0];

int i=0, j=0;
string pre="";

while(true) {
    if(A[0][i] == A[1][j]) {
        pre += A[0][i];
        i++; j++;
    } else {
        break;
    }
}

for(int i = 2; i < A.size(); ++i) {
    bool done=false;
    for(int j = 0; j < pre.size(); ++j) {
        if(!done && A[i][j] != pre[j]) {
            pre.erase(pre.begin()+j, pre.end());
            done = true;
        }
    }
}
return pre;
}