给定输入字符串,要求判断任意子字符串是否对称。
基本思路就是DP
写出DP表达式为 dp[i][j] = dp[i + 1][j - 1] && (s[i] == s[j]) dp[i][j]代表s(i,j)的子串是否对称
注意在for循环赋值时,这里增长的对象其实是子串的长度。
长度为奇数时:
(->代表决定)
dp[0,0]
dp[1,1] -> dp[0,2]
dp[2,2] -> dp[1,3] -> dp[0,4]
dp[3,3] -> dp[2,4] -> dp[1, 5]
...
长度为偶数时:
dp[0,1]
dp[1,2] -> dp[0,3]
dp[2,3] -> dp[1,4] -> dp[0,5]
dp[3,4] -> dp[2,5] -> dp[1,6]
...
因此外层循环变量是长度,内层循环变量是起点
1 def palindrom(s): 2 length = len(s) 3 # Create a 2D array in Python 4 dp = [[False for i in range(length)] for j in range(length)] 5 # length = 1 substring 6 for i in range(length): 7 dp[i][i] = True 8 # length = 2 substring 9 for i in range(length - 1): 10 if s[i] == s[i + 1]: 11 dp[i][i + 1] = True 12 # length = k substring 13 for len3 in range(3, length + 1): 14 for start in range(0, length - len3 + 1): 15 end = start + len3 - 1 16 if s[start] == s[end] and dp[start + 1][end - 1]: 17 dp[start][end] = True 18 19 print dp 20 print dp[0][length - 1] 21 22 palindrom(‘aaaaabbb‘)
时间: 2024-10-11 04:30:26