题解:dp,记录最佳答案位置
最长公共子串
http://www.nowcoder.com/questionTerminal/f33f5adc55f444baa0e0ca87ad8a6aac
import java.util.*; public class Solution { /** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ public String LCS (String str1, String str2) { if(str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0){ return ""; } int[][] dp = new int[str1.length()][]; for(int i = 0;i < str1.length(); i++) { dp[i] = new int[str2.length()]; } for(int i = 0;i < str1.length(); i++) { for(int j = 0;j < str2.length(); j++) { dp[i][j] = 0; } } int ti = 0, tj = 0, ans = 0; for(int i = 0;i < str1.length(); i++) { for(int j = 0;j < str2.length(); j++) { if(str1.charAt(i) == str2.charAt(j)) { if(i > 0 && j > 0) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = 1; } } if(dp[i][j] > ans) { ans = dp[i][j]; ti = i; tj = j; } } } StringBuilder sb = new StringBuilder(); for(int i = 0;i < ans; i++) { sb.append(str1.charAt(ti-ans+1 + i)); } return sb.toString(); } }