Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
count-different-palindromic-subsequences.py 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-12 01:33 +08:00 . remove sensitive question description
# Time: O(n^2)
# Space: O(n^2)
class Solution(object):
def countPalindromicSubsequences(self, S):
"""
:type S: str
:rtype: int
"""
def dp(i, j, prv, nxt, lookup):
if lookup[i][j] is not None:
return lookup[i][j]
result = 1
if i <= j:
for x in xrange(4):
i0 = nxt[i][x]
j0 = prv[j][x]
if i <= i0 <= j:
result = (result + 1) % P
if None < i0 < j0:
result = (result + dp(i0+1, j0-1, prv, nxt, lookup)) % P
result %= P
lookup[i][j] = result
return result
prv = [None] * len(S)
nxt = [None] * len(S)
last = [None] * 4
for i in xrange(len(S)):
last[ord(S[i])-ord('a')] = i
prv[i] = tuple(last)
last = [None] * 4
for i in reversed(xrange(len(S))):
last[ord(S[i])-ord('a')] = i
nxt[i] = tuple(last)
P = 10**9 + 7
lookup = [[None] * len(S) for _ in xrange(len(S))]
return dp(0, len(S)-1, prv, nxt, lookup) - 1
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助