题解 | #最长公共子串#
最长公共子串
http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
dp[i] 用来记录i下标是从 dp[i] 到 i 得到的最长字串,最长字串为 dp[i] 到 i 的下标,其实也是滑动窗口的思想
public String LCS (String str1, String str2) { int[] dp = new int[str1.length()+1]; dp[0] = 0; int count = 0; int max = 0; int[] res = new int[2]; for(int i = 1; i < dp.length; i++) { String tmp = str1.substring(dp[i-1],i); if(str2.contains(tmp)) { dp[i] = dp[i-1]; count++; if(count > max) { max = count; res[0] = dp[i]; res[1] = i; } }else { i = dp[i-1]+1; dp[i] = i; count = 0; } } return str1.substring(res[0],res[1]); }