题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
package main import ( "fmt" ) func max(a, b int) int { if a > b { return a } return b } func longestSubString(s string) int { var length int size := len(s) // dp[i][j]: 标识 s[i,j]是否是对称子串 dp := make([][]bool, size) for i:=0; i<size; i++ { dp[i] = make([]bool, size) } // 初始化 for i:=0; i<size; i++ { dp[i][i] = true } // 动态转移方程 for i:=size-1; i>=0; i-- { for j:=i; j<size; j++ { if s[i] == s[j] && (j-i<=2 || dp[i+1][j-1]) { dp[i][j] = true length = max(length, j-i+1) } } } return length } func main() { var s string fmt.Scan(&s) fmt.Println(longestSubString(s)) }
// 本题输入为一个字符串,所以采用 fmt.Scan(&s)