Simple and explained solution C++


#1

`string Solution::longestCommonPrefix(vector &A) {
int sz_s = A[0].size();
int sz_v = A.size();
int flag=0;
string test = A[0]; // taking base string to check in subsequent string
string ans; // use to store the prefix
for(int i=0; i<sz_s; i++){
flag=0;
for(int j=1; j<A.size(); j++){
string test2 = A[j]; // taking string to check with test string i.e base string
if(i >= test2.size()){flag=1;break;} // encountering smallest string

        if(test[i]!=test2[i]){flag=1;break;} // if character of string is not equal
    }
    if(flag==1)break; // character of string not equal then break from loop
    else if(flag==0 && i==0) ans=test[i]; // first equal character of string
    else if(flag==0 && i>0) ans+=test[i]; // equal characters of string
}
return ans;

}`