题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
//本大神的思考
//将输入的字符串分别用长串和短串存储
//将短串的长度依次减小, 并遍历固定长度下的子串剪切可能
//如果长串包含剪切的子串就返回长度
//否则最后返回0
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
String longStr ;
String shortStr ;
if(str1.length() > str2.length())
{
longStr = str1;
shortStr = str2;
}
else
{
longStr = str2;
shortStr = str1;
}
//len=8 i=5 7 6 5 4 3
int len = shortStr.length();
for (int i = len; i >0 ; i--)
{//长度依次减小
for (int j = 0; j <= len-i ; j++)
{
String tmp = shortStr.substring(j,j+i);
if (longStr.contains(tmp))
{
System.out.println(i);
return;
}
}
}
System.out.println(0);
}
}
华为机试题解 文章被收录于专栏
华为机试题解