gpt4 book ai didi

将字符串从一种格式转换为另一种格式的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:15:15 25 4
gpt4 key购买 nike

我在看一个问题,它声明要按如下方式转换字符串。

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

我能够理解如何做到这一点。

我在想有没有办法以反向的方式做到这一点。当给出像 abcabccdcdcdef 这样的字符串时,我知道可以有很多表示的可能性。我在寻找我们能否以占用最低内存的表示形式来做到这一点(不是算法而是最终字符串)。

最佳答案

为了获得最大效率,我们希望尽可能多地减少。我想我会做这样的事情(它可能不是最有效的算法):

s = "whateverwhateveryouwantwantwantababababababababc"
possibilities = []
repeats = []
def findRepeats(repeats, s, length):
for i in range(0, len(s) - 2 * length + 1):
if s[i:i+length] == s[i+length:i+2*length]:
trackInd = i+length
times = 2
while trackInd+2*length <= len(s):
if (s[trackInd:trackInd+length]==s[trackInd+length:trackInd+2*length]):
times += 1
else: break
trackInd += length

repeats.append((i, times, s[i:i+length]))

return repeats

for i in range(0, len(s)):
repeats = findRepeats(repeats, s, i)

def formPossibility(repeats, s):
build = ""
i = 0
while i < len(s):
pass = True
for repeat in repeats:
if repeat[0] == i:
pass = False
build += repeat[1] + "["
build += repeat[2] + "]"
break

if pass:
build += s[i]

# I didn't finish this but you would loop through all the repeats and test
# them to see if they overlap, and then you would take all the posibilities
# of different ways to make them so that some are there, and some are not.
# in any case, I think that you get the idea.
# I couldn't finish this because I am doing the coding on stackoverflow and
# its like so painful and so hard to debug. also I don't have enough time sorry

关于将字符串从一种格式转换为另一种格式的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42003115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com