Problem: 5. The longest palindromic substring
[TOC]
train of thought
Seeing the question of finding the longest palindrome substring, the first thought is to solve it violently.
Use a first pointer to locate the string head, and then probe backwards from the first+1 position
problem solving method
Python itself provides [::-1] for string transposition, so through the string between the start position and the cursor, after splitting with [:], it is judged whether the string is a palindrome.
Here max_length is used to temporarily save the longest string and avoid repeated loops in the while loop.
the complexity
- time complexity:
Add time complexity, example: O ( nlogn ) O(nlogn)O(nlogn)
- Space complexity:
Add space complexity, example: O ( 1 ) O(1)O(1)
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
start_index = 0
end_index = len(s)
max_length = 0
flag_start = 0
flag_end = 0
if len(s) == 1:
return s
while start_index <= end_index and end_index - start_index > max_length:
for cursor in range(0,len(s)+1):
if s[start_index:cursor] == s[start_index:cursor][::-1]:
if cursor-start_index > max_length:
max_length = cursor-start_index
flag_start = start_index
flag_end = cursor
start_index = start_index + 1
return (s[flag_start:flag_end])
[optimization]
Central Diffusion Algorithm
Later, I saw the optimization algorithm of the central diffusion algorithm for the determination of this palindrome string, which can optimize the time complexity of the worst case of n^2.
The central diffusion algorithm is equivalent to allowing the string to be diffused and detected on both sides, and the method mentioned above has and can only detect backwards, so it is necessary to add a cursor to detect forwards.
problem solving method
After carefully studying the central diffusion algorithm, in fact, my algorithm can achieve similar results in terms of slightly optimized efficiency.
A max_length is reserved in the center diffusion algorithm. If max_length has been defined, then when searching for the longest string, you can directly search for the palindrome string by walking max_length lengths from mid_cursor to both sides.
the complexity
- time complexity:
Add time complexity, example: O ( n ) O(n)O ( n )
- Space complexity:
Add space complexity, example: O ( 1 ) O(1)O(1)
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
start_index = 0
end_index = len(s)
max_length = 0
flag_start = 0
flag_end = 0
if len(s) == 1:
return s
while start_index <= end_index and end_index - start_index > max_length:
for cursor in range(max_length,len(s)+1):
if s[start_index:cursor] == s[start_index:cursor][::-1]:
if cursor-start_index > max_length:
max_length = cursor-start_index
flag_start = start_index
flag_end = cursor
start_index = start_index + 1
return (s[flag_start:flag_end])