首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建动态字符串

创建动态字符串
EN

Stack Overflow用户
提问于 2017-10-15 11:57:14
回答 2查看 1.2K关注 0票数 2

我正在尝试构建某种“动态子字符串”,它是由给定string中的循环构建的。规则是我需要按字母顺序找到最长的substring,如果我有一个潮流,我需要计算这两个值,并打印具有较大值的那个。

我读到在python中,字符已经被赋予了一个数值,因此ab更小;知道这一点,我写了以下内容:

代码语言:javascript
复制
s = "abcsaabcpaosdjaf"
ans = []
# Loop over the string
for i in range(len(s)-1):
    if s[i] < s[i+1]:
        #evaluate if it is in order and build the new string
        ans = s[i]+s[i+1]
    #print the result        
    print(ans)

我的问题是,我不知道如何动态地-我不确定这是否是正确的方式-生成子字符串ans,现在我有了s[i]+s[i+1],但它只给了我一个包含两个字符的列表,实际上是按字母顺序排列的,并且固定为两个。我怎么做才能让它按原样构建呢?

EN

回答 2

Stack Overflow用户

发布于 2017-10-15 12:50:51

尝尝这个。希望评论能解释得够多,但如果你不明白,请不要问。

代码语言:javascript
复制
s= "abcsaabcpaosdjaf"
best_answer = ''
current_answer = s[0]
# Loop over the string
for i in s[1:]:
    # look to see if this letter is after the
    # last letter in the current answer.
    if ord(i) > ord(current_answer[-1]):
        # if it is, add the letter to the current
        # answer
        current_answer += i
    else:
        # if it is not, we check if the current
        # answer is longer than the best
        # answer, and update it to the best
        # answer if it is.
        if len(current_answer) > len(best_answer):
            best_answer = current_answer
        # We then set the current answer
        # to just the last letter read.
        current_answer = i
票数 0
EN

Stack Overflow用户

发布于 2017-10-16 13:41:19

代码语言:javascript
复制
import itertools
s= "abcsaabcpaosdjaf"
result = max(
    (
        list(next(sub)) + [b for a, b in sub]
        for ascending, sub in itertools.groupby(zip(s,s[1:]), lambda x: x[0] <= x[1])
        if ascending
    ),
    key=len
)

print (''.join(result))

致谢给this

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46751527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档