Write a function to find the longest common prefix string amongst an array of strings.
Solution1:
Idea: No ingenious method was thought of. Use recursion violence to do it hard. found that as long as the idea, recursion how to do can achieve the method ...
First alphabetical order, if the entire stringarray is empty wine directly returned empty string "", the first string is empty directly returns an empty string. Takes the first string to the first char, then iterates through the first one of each string, and updates each string at the same time, which is to subtract the first letter of each string.
If each string has the first string to the first letter, the output first letter plus recursion checks the new string array after the longest common prefix.
Public classSolution { PublicString Longestcommonprefix (string[] strs) {arrays.sort (STRs); if(strs.length==0) { return""; } if(Strs[0].length () ==0) { return""; } CharCheck=strs[0].charat (0); String m=strs[0]; strs[0]=m.substring (1); for(inti=1;i<strs.length;i++) { if(Check!=strs[i].charat (0)) { return""; } String prev=Strs[i]; Strs[i]=prev.substring (1); } returncheck+Longestcommonprefix (STRs);}}
Solution 2:
It's just a matter of checking each char on the line. Another version was made.
Public classSolution { PublicString Longestcommonprefix (string[] strs) {if(strs==NULL|| Strs.length==0) { return""; } for(intI=0;i<strs[0].length (); i++) { for(intj=0;j<strs.length;j++) { if(Strs[j].length () <=i| | Strs[0].charat (i)! =Strs[j].charat (i)) { returnStrs[0].substring (0, i); } } } returnStrs[0];}}
Longest Common Prefix