题解 | 最长公共子串
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
package main /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ func LCS( str1 string , str2 string ) string { // write code here m, n := len(str1), len(str2) dp := make([][]int, m+1) for i:=0; i<m+1; i++{ dp[i] = make([]int, n+1) } var maxLen = 0 var pos = 0 for i:=1; i<m+1; i++{ for j:=1; j<n+1; j++{ if str1[i-1] == str2[j-1]{ dp[i][j] = dp[i-1][j-1] + 1 } else { dp[i][j] = 0 } if dp[i][j] > maxLen{ // 说明出现更长的连续子串 maxLen = dp[i][j] pos = i-1 } } } return str1[pos-maxLen+1:pos+1] }