题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner;
public class Main {
public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String str1 = scan.next(); String str2 = scan.next(); String shortStr = str1.length() <= str2.length() ? str1 : str2; String longStr = str1.length() <= str2.length() ? str2 : str1; int shortLen = shortStr.length(); int maxLen = 0; String retStr = ""; for (int i = 0; i < shortLen; i++) { if (shortLen - i <= maxLen) { break; } for (int b = i, k = shortLen; k - b > maxLen; k--) { String sub = shortStr.substring(b, k); if (longStr.contains(sub) && sub.length() > maxLen) { maxLen = sub.length(); retStr = sub; break; } } } System.out.println(retStr); } }
}