题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
JAVA
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str1 = sc.nextLine(); String str2 = sc.nextLine(); //判断长度 String longStr = (str1.length() > str2.length())? str1:str2; String shortStr = (str1.length() < str2.length())? str1:str2; String maxLenStr = ""; for(int i=0;i<shortStr.length();i++){ for(int j=i+1;j<shortStr.length();j++){ //找到最长的公共子串 String subStr = shortStr.substring(i,j+1); if(longStr.contains(subStr) && subStr.length() > maxLenStr.length()){ //开始找到最长的公共子串的处理。 maxLenStr = subStr; } } } System.out.println(maxLenStr); } } }