一、原题
Write a function to find the longest common prefix string amongst an array of strings.
二、中文
写一个函数找出一个字串所数组中的最长的公共前缀。
三、举例
str1 = “abcmmm”str2 = “abchhhh”其公共字符串就是 abc
四、思路
五、程序
package LeetCode;
public class Leetcode010 {
private static int longPrefixNum;
public static void main(String[] args) {
System.out.println(longestCommonPrefix("abcduuuu", "abcnmwewe"));
}
/**
* @param str1 字符串1
* @param str2 字符串2
* @return 返回字符串的最长公共前缀
*/
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);
}
}
abc