题解 | #密码截取#
密码截取
http://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
package main
import "fmt"
func main() {
var s string
for {
_, err := fmt.Scan(&s)
if err != nil {
break
}
fmt.Println(longestPalindrome(s))
}
}
func longestPalindrome(s string) int {
dp := make([][]int, len(s))
for i := 0; i < len(s); i++ {
dp[i] = make([]int, len(s))
dp[i][i] = 1
}
//初始化
max := 1
for i := len(s)-2; i >= 0;i-- {
for j := i+1; j < len(s); j++ {
if s[i]==s[j] {
if dp[i+1][j-1]==1 {
dp[i][j]=1
} else if j - i <= 1 {
dp[i][j] = 1
}
if dp[i][j]== 1 && max < j-i+1{
max = j-i+1
}
}
}
}
return max
}
import "fmt"
func main() {
var s string
for {
_, err := fmt.Scan(&s)
if err != nil {
break
}
fmt.Println(longestPalindrome(s))
}
}
func longestPalindrome(s string) int {
dp := make([][]int, len(s))
for i := 0; i < len(s); i++ {
dp[i] = make([]int, len(s))
dp[i][i] = 1
}
//初始化
max := 1
for i := len(s)-2; i >= 0;i-- {
for j := i+1; j < len(s); j++ {
if s[i]==s[j] {
if dp[i+1][j-1]==1 {
dp[i][j]=1
} else if j - i <= 1 {
dp[i][j] = 1
}
if dp[i][j]== 1 && max < j-i+1{
max = j-i+1
}
}
}
}
return max
}