Topic:
Write a function to find the longest common prefix string amongst an array of strings.
That is, the public prefix of a given set of strings is obtained.
Thinking Analysis:
One looks for the prefix, compares the first and second, finds the public prefix, then the public prefix and the third comparison, looks for the common prefix, and so on.
C + + Reference code:
classsolution{ Public:stringLongestcommonprefix ( vector<string>&strs) {if(Strs.empty ()) {return ""; }stringCommon = strs[0]; vector<string>:: Size_type size = Strs.size ();intLength//Save the minimum length of the two strings to be compared, only within the minimum length range intCount//record equal number of characters for(inti =1; i < size; i++) {length = min (Common.length (), strs[i].length ()); Count =0; for(intj =0; J < length; J + +) {//If two characters typeface etc count++ if(Strs[i][j] = = Common[j]) {count++; }//If two characters are not equal to exit the inner loop directly Else{ Break; } }The common prefix of common and strs[i] is saved in common, and the next character is comparedCommon = Common.substr (0, count); }returnCommon }};
C # Reference Code:
Public class solution{ PublicString Longestcommonprefix (string[] strs) {if(STRs = =NULL|| STRs. Length = =0) {returnString. Empty; } stringCommon= strs[0];intLength =0;int Count=0; for(inti =1; I < STRs. Length; i++) {length = Math.min (Common. Length, Strs[i]. Length);Count=0; for(intj =0; J < length; J + +) {if(Strs[i][j] = =Common[j]) {Count++; }Else{ Break; } }Common=Common. Substring (0,Count); }return Common; }}
Python Reference Code:
class solution: # @return A string def longestcommonprefix(self, STRs):size = Len (STRs)if notSTRsorSize = =0:return ""Common = strs[0] Length =0Count =0 forIinchRange1, size): Length = min (len (Common), Len (Strs[i])) Count =0 forJinchRange (length):ifSTRS[I][J] = = Common[j]: Count + =1 Else: BreakCommon = common[0: Count]returnCommon
Leetcode:longest Common Prefix