If there is only one string array, then the longest prefix is itself; if there are more than one, we set the first to the current longest prefix, take the current longest prefix to the second comparison, and then select the longest prefix, one back!
Code:
#include <iostream>#include<string>#include<vector>using namespacestd;stringLongestcommonprefix (vector<string> &STRs) { intL =strs.size (); if(L <1 ) { return ""; } stringprefix = strs[0]; for(inti =1; i < L; i++) { intLpre =prefix.size (); intLnow =strs[i].size (); intLQ = Lpre>lnow?Lnow:lpre; intJ; for(j =0; J < LQ; J + +) { if(Prefix[j]! =Strs[i][j]) Break; } if(J = =Lnow) {prefix=Strs[i]; } Else{prefix= Strs[i].substr (0, J); } } returnprefix;}intmain () {vector<string> STRs = {"Asdqwer"," as","Asdklj"}; cout<< Longestcommonprefix (STRs) <<Endl;}
Leetcode Longest Common Prefix