Write a function to find the longest common prefix string amongst an array of strings.
This is the longest common prefix for finding a set of strings, for example:
"ABC" "a" obviously lprefixstring = "a", pay attention to check the situation of empty strings!!!
Contact using sequential programs, and recursion to solve the above problems:
classSolution { Public: stringLongestcommonprefix (vector<string> &STRs) { intNSize =strs.size (); intNprefixnum =Int_max; if(NSize = =0) { return ""; } stringIcompare (strs[0]); for(intI=0; i< nSize; ++i) {inttemp =0; if(icompare.size () = =0|| Strs[i].size () = =0) return ""; string:: Size_type Iscana =0; string:: Size_type iscanb =0; while(Iscana! = icompare.size () && iscanb! =strs[i].size ()) { if(Icompare[iscana] = =STRS[I][ISCANB]) {Temp++; Iscana++; ISCANB++; } Else { Break; } } if(Temp <nprefixnum) {Nprefixnum=temp; Icompare=Strs[i]; } } stringret; Ret.assign (Icompare,0, Nprefixnum); returnret;}};
classSolution { Public: stringLongestcommonprefix (vector<string> &STRs) { intNSize =strs.size (); if(NSize = =0) { return ""; } stringIcompare (strs[0]); intNprefix =Int_max; Findlongestprefix (STRs, Icompare,0, Nprefix); returnIcompare.assign (Icompare,0, Nprefix);}voidFindlongestprefix (vector<string> &strs,string&SRC1,intIint&nprefixnum) { string:: Size_type Iscana =0; string:: Size_type iscanb =0; inttemp =0; stringSrc2 (Strs[i]); while(Iscana! = src1.size () && iscanb! =src2.size ()) { if(src1.size () = =0|| Src2.size () = =0) { return ; } if(Src1[iscana] = =SRC2[ISCANB]) {Temp++; Iscana++; ISCANB++; } Else { Break; } } intNSize =strs.size (); if(i+1==nSize) { if(Temp <nprefixnum) Nprefixnum=temp; return ; } if(Temp <nprefixnum) {src1.assign (SRC1,0, temp); Nprefixnum=temp; Findlongestprefix (STRs, SRC1, I+1, Nprefixnum); } Else{findlongestprefix (STRs, SRC1, I+1, Nprefixnum); } }};
In a word, you have to work hard to look effortless!
Leetcode Longest Common Prefix