Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
encode-string-with-shortest-length.py 1017 Bytes
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-12 01:33 +08:00 . remove sensitive question description
# Time: O(n^3) on average
# Space: O(n^2)
class Solution(object):
def encode(self, s):
"""
:type s: str
:rtype: str
"""
def encode_substr(dp, s, i, j):
temp = s[i:j+1]
pos = (temp + temp).find(temp, 1) # O(n) on average
if pos >= len(temp):
return temp
return str(len(temp)/pos) + '[' + dp[i][i + pos - 1] + ']'
dp = [["" for _ in xrange(len(s))] for _ in xrange(len(s))]
for length in xrange(1, len(s)+1):
for i in xrange(len(s)+1-length):
j = i+length-1
dp[i][j] = s[i:i+length]
for k in xrange(i, j):
if len(dp[i][k]) + len(dp[k+1][j]) < len(dp[i][j]):
dp[i][j] = dp[i][k] + dp[k+1][j]
encoded_string = encode_substr(dp, s, i, j)
if len(encoded_string) < len(dp[i][j]):
dp[i][j] = encoded_string
return dp[0][len(s) - 1]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助