1. Question
Find the longest common prefix of the string array, which is all strings.
Write a function to find the longest common prefix string amongst an array of strings.
2. Solution (O (MN))
With the first string as the prefix initial value (the prefix cannot be longer than it can be optimized to use the shortest length string as the initial value string), traverse all strings, the current string and the prefix variable of the public prefix, as a new prefix variable.
Consider special cases: arrays are empty or array lengths are 0
Importjava.util.Arrays;Importjava.util.LinkedList; Public classSolution {//O (MN) PublicString Longestcommonprefix (string[] strs) {if(Strs.length = = 0 ) return""; intLen = strs[0].length (); intK = 0; for(intI=1; i<strs.length; i++ ) if(Strs[i].length () <Len) {Len=strs[i].length (); K=i; } String prefix=Strs[k]; for(inti=0; i<strs.length; i++){ if( !strs[i].startswith (prefix)) {prefix= prefix.substring (0, Prefix.length ()-1 ); I--; } } returnprefix; }}
View Code
or a comparison:
Importjava.util.Arrays;Importjava.util.LinkedList; Public classSolution {//O (MK) PublicString Longestcommonprefix (string[] strs) {if(Strs.length = = 0 ) return""; intK = 0; for(intI=1; i<strs.length; i++ ) if(Strs[i].length () <strs[k].length ()) K=i; intLen =strs[k].length (); inti; for(i=0; i<len; i++ ){ BooleanJudge =true; for(intj=0; Judge && j<strs.length; J + +) Judge= Judge && (Strs[j].charat (i) = =Strs[k].charat (i)); if(Judge = =false ) Break; } returnStrs[k].substring (0, i); }}
View Code
It is also possible to use recursion, that is, the longest common prefix is the longest public prefix of the first n-1 string and the last one of the most common prefixes:
Importjava.util.Arrays;Importjava.util.LinkedList; Public classSolution {//Use iteration, O (n2) PublicString Longestcommonprefix (string[] strs) {if(Strs.length = = 0 ) return""; if(Strs.length = = 1 ) returnStrs[0]; returnLongestcommonprefix (NewLinkedlist<string>(Arrays.aslist (STRs))); } PublicString Longestcommonprefix (linkedlist<string>STRs) { if(strs.size () = = 2) {String S1=Strs.getfirst (); String S2=Strs.getlast (); intLen = (S1.length () < S2.length ())?s1.length (): S2.length (); inti = 0; for(; I<len && S1.charat (i) = = S2.charat (i); i++); returnS1.substring (0, i); } LinkedList<String> temp =NewLinkedlist<string>(); Temp.add (Strs.removelast ()); Temp.add (Longestcommonprefix (STRs)); returnLongestcommonprefix (temp); }}
View Code
Longest common prefix