File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 5959
6060// @lc code=start
6161func longestPalindrome (s string ) string {
62+ n := len (s )
63+ if n <= 1 {
64+ return s
65+ }
66+ // begin 和 max_length 为当前最长回文子串的开始位置和长度
67+ max_len := 1
68+ begin := 0
69+ dp := make ([][]bool ,n )
70+ // 长度为 1 的字符串均为回文串
71+ for i := 0 ;i < n ;i ++ {
72+ dp [i ] = make ([]bool ,n )
73+ dp [i ][i ] = true
74+ }
6275
76+ // 枚举子串长度,从 2 开始,最长为 n
77+ for L := 2 ;L < n + 1 ;L ++ {
78+ // 枚举左边界
79+ for left := 0 ;left < n ;left ++ {
80+ // 固定字符串长度下的右边界
81+ right := L + left - 1
82+ // 右边界越界,则退出此长度下的循环
83+ if right >= n {
84+ break
85+ }
86+ // 如果左右边界字符不同,则一定不是回文串
87+ if s [left ] != s [right ]{
88+ dp [left ][right ] = false
89+ } else {
90+ // right - left <= 2 等价于 字符串长度 <= 3
91+ // 此时只需要字符串左右两端字符相等,即为回文串
92+ if right - left <= 2 {
93+ dp [left ][right ] = true
94+ } else {
95+ // 该情况下,字符串左右边界符合回文串条件,
96+ // 改字符串是否为回文串要根据左右各缩进一位的字符串是否为回文串来进行判断
97+ dp [left ][right ] = dp [left + 1 ][right - 1 ]
98+ }
99+ }
100+ // 更新最长回文子串
101+ if dp [left ][right ] && right - left + 1 > max_len {
102+ max_len = right - left + 1
103+ begin = left
104+ }
105+ }
106+ }
107+ return s [begin :begin + max_len ]
63108}
64109// @lc code=end
65110
You can’t perform that action at this time.
0 commit comments