No.14,longest Common Prefix
The input to this question is an array of strings, from which the longest common prefix is found.
Idea: Start with the first string and the second string to find the longest common prefix, compare the longest public prefix to the third string, and so on, traverse all the strings to find the last common prefix.
The optimization point is that the length of the longest public prefix must be less than or equal to the length of the shortest string, optimizing the number of comparisons.
Public classSolution { PublicString Longestcommonprefix (string[] strs) {if(strs.length==0) return""; if(strs.length==1) returnStrs[0]; intLength=strs[0].length (); String prefix=strs[0]; for(inti=1;i<strs.length;i++) {length=math.min (length, strs[i].length ()); String Str=Strs[i]; intJ; for(j=0;j<length;j++){ if(Prefix.charat (j)! =Str.charat (j)) { Break; }} prefix=prefix.substring (0, J); Length=math.min (length, prefix.length ()); } returnprefix; }}
[Leetcode] Longest Common Prefix