题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str1 = in.nextLine(); String str2 = in.nextLine(); getMaxPublicStr(str1, str2); } } /** * 查找两个字符串a,b中的最长公共子串 * 查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。 * 双指针: 指向短的字符串, 然后遍历 长字符串.contains() */ public static void getMaxPublicStr(String str1, String str2) { if (str1.length() > str2.length()) { String temp = str1; str1 = str2; str2 = temp; } String result = ""; int left = 0; int right = left + 1; while (right <= str1.length()) { String substr = str1.substring(left, right); if (str2.contains(substr)) { //表示包含该子串 if (substr.length() > result.length()) { result = substr; right ++; } } else { //不包含子串 left++; right++; } } System.out.println(result); } }