1. 暴力解法

  1. // 暴力解法
  2. func longestPalindrome(s string) string {
  3. maxLen := 0
  4. maxString := ""
  5. for i := 0; i < len(s); i++{
  6. for j := i + 1; j <= len(s); j++{
  7. if isPalindrome(s[i:j]) && len(s[i:j]) > maxLen{
  8. maxString = s[i:j]
  9. maxLen = len(s[i:j])
  10. }
  11. }
  12. }
  13. return maxString
  14. }
  15. func isPalindrome1(s string) bool {
  16. len := len(s)
  17. for i := 0; i < len / 2; i++{
  18. if s[i] != s[len-i-1]{
  19. return false
  20. }
  21. }
  22. return true
  23. }
  24. func longestPalindrome1(s string) string {
  25. var maxLen int
  26. var maxStr string
  27. for i := 0; i < len(s); i++ {
  28. for j := i + 1; j < len(s)+1; j++ {
  29. len := isPalindrome1(s[i:j])
  30. if len > maxLen {
  31. maxStr = s[i:j]
  32. maxLen = len
  33. }
  34. }
  35. }
  36. return maxStr
  37. }
  38. func isPalindrome1(s string) int {
  39. var newStr string
  40. for i := len(s)-1; i >= 0; i--{
  41. newStr += s[i:i+1]
  42. }
  43. if s == newStr {
  44. return len(s)
  45. }
  46. return 0
  47. }

时间复杂度:两层 for 循环 O(n²),for 循环里边判断是否为回文 O(n),所以时间复杂度为 O(n³)。
空间复杂度:O(1),常数个变量。

2. 动态规划

  1. func longestPalindrome(s string) string {
  2. if len(s) < 2{
  3. return s
  4. }
  5. //状态容器
  6. dp := make([][]bool, len(s))
  7. for i := range dp {
  8. dp[i] = make([]bool, len(s))
  9. }
  10. for i := 0; i < len(s); i++{
  11. dp[i][i] = true
  12. }
  13. maxLen := 1
  14. begin := 0
  15. for j := 1; j < len(s); j++{
  16. for i := 0; i < len(s) - 1 && i < j; i++{
  17. if s[i] != s[j]{
  18. dp[i][j] = false
  19. }else{
  20. if j - i < 3{
  21. dp[i][j] = true
  22. }else{
  23. dp[i][j] = dp[i+1][j-1]
  24. }
  25. }
  26. // 只要 dp[i][j] == true 成立,就表示子串 s[i..j] 是回文,此时记录回文长度和起始位置
  27. if dp[i][j] && j - i + 1 > maxLen{
  28. maxLen = j - i + 1
  29. begin = i
  30. }
  31. }
  32. }
  33. return s[begin:begin+maxLen]
  34. }

111.png

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

参考:

https://www.bilibili.com/video/BV1AA411B7XV?from=search&seid=16080201134773088835&spm_id_from=333.337.0.0

https://segmentfault.com/a/1190000023738028

https://leetcode-cn.com/problems/longest-palindromic-subsequence/solution/zi-xu-lie-wen-ti-tong-yong-si-lu-zui-chang-hui-wen/