Small two long time no update blog, it is a sin, recently in the look at the Linux things lead to progress delays, so tonight before bedtime anger brush a problem!
Problem Description:
Write a function to find the longest common prefix string amongst an array of strings.
Problem Solving Ideas:
The problem is to find the longest identical front string inside all the array strings. So my idea is to first find the shortest string in the array, and then each time the comparison of the maximum loop the length of the line, so as to avoid the string subscript overflow problem. Sets the StringBuilder object to hold the same characters. Then begins the loop, for each character of the string, takes the position of the first string in the array as a reference, and if there is a string that does not match the character at that position, returns the StringBuilder object that was received, otherwise the loop continues. Finally, return the StringBuilder object that was received.
The code is as follows:
1 Public classSolution {2 PublicString Longestcommonprefix (string[] strs) {3 intLength =Integer.max_value;4StringBuilder StringBuilder =NewStringBuilder ();5 if(Strs.length = = 0 | | strs = =NULL)6 return"";7 if(Strs.length = = 1)8 returnStrs[0];9 for(inti = 0; i < strs.length; i++) {TenLength = (strs[i].length () < length)?strs[i].length (): length; One } A if(length = = 0) - return""; - for(intj = 0; J < length; J + +) { the for(inti = 0; i < strs.length; i++) { - if(Strs[i].charat (j)! = Strs[0].charat (j)) - returnstringbuilder.tostring (); - } +Stringbuilder.append (strs[0].charat (j)); - } + returnstringbuilder.tostring (); A } at}
Java [Leetcode] Longest Common Prefix