?要求:接收两个字符串,返回其最长公共子串
?思路:由长到短在较短字符串中截取子串,判断是否是较长字符串的子串
例如 “xxabd” 和“abc” 较短字符串为“abc”,故先截取“abc”进行判断,再截取“ab”,“bc”判断,最后截取“a”,“b”,“c”判断
?涉及函数:str1.contains(str2) 判断str2是否为str1子串 返回true/false
?????????????????? str1.substring(begin,end) 在str1中截取第begin到end的字符 返回截取的字符串
public static String Get_ms(String str1, String str2)
{
// 判断为空指针或者空串
if (str1 == null || str2 == null || str1.equals("") || str2.equals(""))
{
return null;
}
// 使str1为较短字符串
if (str1.length() > str2.length())
{
String tmp = "";
tmp = str1;
str1 = str2;
str2 = tmp;
}
int len1 = str1.length(), len2 = str2.length();
// System.out.println(len1);
// 遍历较短字符串str1
/* 由大到小选取较短字符串的子串,判断长字符串是否有此子串 */
String ans = "";
for (int i = 0; i < len1; i++)
{
int begin = 0, end = len1 - i;
for (; end <= len1; end++, end++)
{
ans = str1.substring(begin, end);
if (str2.contains(ans))
return ans;
}
}
return null;
}
?????????????????? 作为一只悲惨的菜鸟,不知道上述函数浪费了很多时间
比如:写了以下代码用来得到子串
public static String Get_substring(String str, int begin, int end)
{
if (str == null || str.equals("") || begin >= end || begin < 0 || end > str.length())
return null;
char[] strc = str.toCharArray();
char[] temp = new char[end - begin];
String ans = "";
for (int i = begin; i < end; i++)
{
temp[i] = strc[i];
}
ans = String.valueOf(temp);
return ans;
}
再比如:又写了以下代码用来判断是否是子串
public static boolean IsSubstring(String str1, String str2)
{
char[] strc1 = str1.toCharArray();
char[] strc2 = str2.toCharArray();
for (int key = 0; key < str2.length() - str1.length(); key++)
{
int i = key, j = 0;
for (; j < str1.length(); i++, j++)
{
if (strc2[i] != strc1[j])
{
break;
}
}
if (j == str1.length())
return true;
}
return false;
}
|