LeetCode -- Longest Common Prefix, longestprefixmatch
Write a function to find the longest common prefix string amongst an array of strings.
Returns the longest common prefix of all strings.
Idea: first compare the public part of the first two strings, put the public part in the prefix, and then get the new prefix by comparing the prefix with the third one, so that the loop can be done, if the two characters are different, the system jumps out of the loop.
Public class LongestCommonPrefix {
Public static void main (String [] args ){
String [] strs = {"hello", "hello", "El "};
String prefix = strs [0];
For (int I = 1; I <strs. length; ++ I ){
Prefix = findCommonLongestPrefix (prefix, strs [I]);
}
System. out. println (prefix );
}
Public static String findCommonLongestPrefix (String prefix, String current ){
StringBuffer sb = new StringBuffer ();
Int len = prefix. length ()> current. length ()? Current. length (): prefix. length ();
For (int I = 0; I <len; ++ I ){
If (prefix. charAt (I) = current. charAt (I )){
Sb. append (prefix. charAt (I ));
} Else {
Break;
}
}
Return sb. toString ();
}
}