Cho chuỗi S (độ dài ≤ 1000). Tìm độ dài xâu con palindrome dài nhất.
Ví dụ: "BABAC" → 3 (xâu con "BAB").
Quy trình giải quyết (Dynamic Programming)
- Tạo ma trận DP
n x nkhởi tạoFalse. - Đặt đường chéo chính
DP[i][i] = True. - Duyệt độ dài
ltừ 2 đếnn:- Với mỗi
i, tínhend = i + l. - Nếu
l == 2vàS[i] == S[end-1]:DP[i][end-1] = True. - Nếu
l > 2vàS[i] == S[end-1]vàDP[i+1][end-2]:DP[i][end-1] = True. - Khi đặt
True, cập nhậtmax_length = l,start = i.
- Với mỗi
- Trả về
max_length.
Ví dụ mã nguồn
class Solution:
def solve(self, s):
dp = [[False for i in range(len(s))] for i in range(len(s))]
for i in range(len(s)):
dp[i][i] = True
max_length = 1
start = 0
for l in range(2, len(s) + 1):
for i in range(len(s) - l + 1):
end = i + l
if l == 2:
if s[i] == s[end - 1]:
dp[i][end - 1] = True
max_length = l
start = i
else:
if s[i] == s[end - 1] and dp[i + 1][end - 2]:
dp[i][end - 1] = True
max_length = l
start = i
return max_length
ob = Solution()
print(ob.solve('BABAC')) # Output: 3
Đầu vào
"ABBABBC"
Đầu ra
5