Professional Documents
Culture Documents
Substring
Yang Liu
Problem
Given a string S
Find the longest palindromic
substring in S.
Example:
S=abcbcbb. The longest palindromic
substring is bcbcb.
Length=n-1(5) substring:
start=0, end=n-2(4): abcbc---not
palindromic
start=1, end=n-1(5): bcbcb---palindromic
For len=n to 2
len n
n len
for start=0 to n-len
start 0
end= start+len-1
if substring(start,end) is palindromic
return substring(start,end)
Return first character
Complexity
n len
len n
start 0
len
3
(
n
len
1
)
len
O
(
n
)
len n
len
Dynamic Programming(DP)
If substring(i,j) is palindromic, then
substring(i+1,j-1) is palindormic
P[i,j]=1 if substring(I,j) is palindormic
=0 otherwise
When j-i is small(=0, 1), easy to know:
P[i,i]=1 and P[i,i+1]=(S[i]==S[j])
(base)
Computer P[i,j] from small j-i to big j-i:
P[i,j]=P[i+1,j-1] && S[i]==S[j]
Example of DP
S=abcbcbb
P[i,i
]
1
1
1
1
1
1
1
Example of DP
S=abcbcbb
P[i,i
]
P[i,i+
1]
0
1
0
1
0
1
0
1
0
1
1
1
Example of DP
S=abcbcbb
P[i,i
]
P[i,i+
1]
P[i,i+
2]
P[i,i+
3]
1
1
Example of DP
S=abcbcbb
P[i,i
]
P[i,i+
1]
P[i,i+
2]
P[i,i+
3]
.
.
.
1
1
Example of DP
S=abcbcbb
P[i,i
]
P[i,i+
1]
P[i,i+
2]
P[i,i+
3]
.
.
.
Max palindromic
substring?
for(len=n to 1)
for(i=0 to n-len)
0
if (P[i,i+len-1])
0
return S[i..i+len
1
1
DP Algorithm
for(i=0 to n-1)
P[i,i]=1;
O(n2) time and space
P[i,i+1]=(S[i]==S[i+1])?1:0;
for(len=3 to n)
for(i=1 to n-len+1)
P[i,i+len-1]=(P[i+1,i+len-2] && S[i]==S[i+len])?1:0
for(len=n to 1)
for(i=0 to n-len)
if (P[i,i+len-1])
return S[i..i+len-1]
O(n) Algorithm
For(i=1 to n-1)
Why the complexity
insert special character before A[i]
center=0;
rEdge=0;
For(i=1 to 2n-1)
image=2*center-i;
P[i]=min(P[image],rEdge-i+1);
extend P[i] to its maximum;
if(P[i]+i>rEdge)
rEdge=P[i]+I;
center=i;
Find the maximum P[i] for i in 1, 3, , 2n-1.
Return the substring centered at i with 2P[i]-1 characters.
is O(n
Exercise 1
Find one of the longest paralindromic
subsequences.
Example:
S=abbbcccabaa
Longest paralindormic subsequenc:
abccba from abbbcccabaa
Exercise 2
Determine whether an integer is a
palindrome. Do this without extra
space.
Research Reference
A New Linear-Time On-Line
Algorithm for finding the smallest
initial palindrome of a string, G.
Manacher, JACM 22(3):346-351,
1975.