每日一题---5. 最长回文子串[力扣][Go]

简介: 每日一题---5. 最长回文子串[力扣][Go]

题目描述

给你一个字符串 s,找到 s 中最长的回文子串。

解题思路

1.如何判断一个字符串是回文(从中间开始左右两边同时移动,如果左边等于右边就是回文串

2.还有就是如何判断下标就是在中间(下标把整个字符串都遍历一遍才能找到最长的那个)

解题代码

暴力破解

所有例子都能通过,只是时间复杂度太高O(n^3),超时

func isHuiWen(s string) bool {
  slen := len(s)
  for i,_ := range s {
    if s[slen - i -1] != s[i] {
      return false
    }
  }
  return true
}
func longestPalindrome(s string) string {
  frontIndex := 0
  afterIndex := 1
  frontIndexMax := 0
  afterIndexMax := 0
  len := len(s)
  for frontIndex <= len {
    for afterIndex <= len {
      s2 := s[frontIndex:afterIndex]
      if isHuiWen(s2) {
        if afterIndexMax - frontIndexMax < afterIndex - frontIndex {
          afterIndexMax = afterIndex
          frontIndexMax = frontIndex
        }
      }
      afterIndex ++
    }
    frontIndex ++
    afterIndex = frontIndex + 2
  }
  return s[frontIndexMax:afterIndexMax]
}

折中遍历法

func longestPalindrome02(s string) string {
  frontIndex := 0
  afterIndex := 0
  i := -1
  for i < len(s) - 1 {
    i++
    i := GetAns(i, s, &frontIndex, &afterIndex)
    i ++
  }
  return s[afterIndex:frontIndex + 1]
}
// 获取前标和后标
func GetAns(after int,s string,frontIndex *int,afterIndex *int) int {
  front := after
  i := len(s)
  for front < i - 1 && s[front + 1] == s[after] {
    front++
  }
  ans := front
  for after > 0 && front < i - 1 && s[front + 1] == s[after - 1] {
    after--
    front++
  }
  if *frontIndex - *afterIndex < front - after {
    *frontIndex = front
    *afterIndex = after
  }
  return ans
}

提交结果

第一种运行超时

第二种:


相关文章
|
2月前
|
Go C++
【力扣】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
【2月更文挑战第18天】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
40 6
|
2月前
|
Go C++
【力扣】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
【2月更文挑战第17天】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
34 8
每日一题 --- 942. 增减字符串匹配[力扣][Go]
每日一题 --- 942. 增减字符串匹配[力扣][Go]
每日一题 --- 942. 增减字符串匹配[力扣][Go]
|
算法 Go
每日一题 --- 442. 数组中重复的数据[力扣][Go]
每日一题 --- 442. 数组中重复的数据[力扣][Go]
每日一题 --- 442. 数组中重复的数据[力扣][Go]
每日一题 --- 933. 最近的请求次数[力扣][Go]
每日一题 --- 933. 最近的请求次数[力扣][Go]
每日一题 --- 933. 最近的请求次数[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
每日一题 --- 606. 根据二叉树创建字符串[力扣][Go]
每日一题 --- 606. 根据二叉树创建字符串[力扣][Go]
每日一题 --- 606. 根据二叉树创建字符串[力扣][Go]
|
Go 索引
每日一题 ---- 599. 两个列表的最小索引总和[力扣][Go]
每日一题 ---- 599. 两个列表的最小索引总和[力扣][Go]
每日一题 ---- 599. 两个列表的最小索引总和[力扣][Go]
|
存储 测试技术 Go
每日一题 --- 393. UTF-8 编码验证[力扣][Go]
每日一题 --- 393. UTF-8 编码验证[力扣][Go]
每日一题 --- 393. UTF-8 编码验证[力扣][Go]
每日一题 --- 590. N 叉树的后序遍历[力扣][Go]
每日一题 --- 590. N 叉树的后序遍历[力扣][Go]
每日一题 --- 590. N 叉树的后序遍历[力扣][Go]