First, the original question
Write a function to find the longest common prefix string amongst an array of strings.
Second, Chinese
Write a function to find the longest public prefix in an array of strings.
Iii. Examples
str1 = "Abcmmm" str2 = "abchhhh" Its common string is ABC
Iv. train of Thought
The first step is to find the smallest length of the string, and then find the shortest most common prefix compared to its string.
v. Procedures
Package Leetcode;
public class Leetcode010 {
private static int longprefixnum;
public static void Main (string[] args) {
System.out.println (longestcommonprefix ("Abcduuuu", "Abcnmwewe"));
/**
* @param str1 string 1
* @param str2 string 2
* @return returns the longest common prefix for a string/public
static String Longestcommonprefix (String str1, String str2) {
if (str1 = = NULL | | str1.length () < 0 | | str2 = NULL | | str2 . Length () < 0) {return
null;
}
int len1 = Str1.length ();
int len2 = Str2.length ();
Longprefixnum = 0;
if (Len1 > Len2) {for
(int i = 0; i < len2; i++) {
if (Str1.charat (i) = = Str2.charat (i)) {
longprefixnum+ +;
} else{break;}}}
else{for
(int i = 0; i < len1 i++) {
if (Str1.charat (i) = = Str2.charat (i)) {
longprefixnum++;
} else{break
;
}}} Return str1.substring (0, Longprefixnum);
}
--------------------------Output--------------------------------
Abc