📅  最后修改于: 2023-12-03 15:42:15.689000             🧑  作者: Mango
门| GATE-CS-2004 |第 86 题
给定一个由字符'0'和'1'组成的字符串s,现在在该字符串中进行一些操作,操作步骤如下:
例如,字符串‘11011’可以进行操作,得到结果字符串‘00100’。
输入: s = '11011'
输出: '00100'
def find_longest_palindrome(s):
s_reverse = s[::-1]
m, n = len(s), len(s_reverse)
max_len = 0
end = 0
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s[i-1] == s_reverse[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
end = i - 1
else:
dp[i][j] = 0
return s[end-max_len+1:end+1]
def reverse(s):
return s[::-1]
def replace_0_1(s):
new_s = ''
for i in range(len(s)):
if s[i] == '0':
new_s += '1'
else:
new_s += '0'
return new_s
def find_replaced_palindrome(s):
longest_palindrome = find_longest_palindrome(s)
replaced_palindrome = replace_0_1(longest_palindrome)
reversed_replaced_palindrome = reverse(replaced_palindrome)
n = len(s)
for i in range(n):
if s[i:i+len(longest_palindrome)] == longest_palindrome:
return s[:i] + reversed_replaced_palindrome + s[i+len(longest_palindrome):]
i += 1
s = '11011'
print(find_replaced_palindrome(s)) # '00100'