如何返回按字母顺序排列的子字符串? [英] How to return alphabetical substrings?

查看:90
本文介绍了如何返回按字母顺序排列的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将字符串 s 作为输入并返回 s 中按字母顺序排列的子字符串列表.例如,s = 'acegibdh' 应该返回 ['acegi', 'bdh'].

这是我想出的代码:

s = 'acegibdh'答案 = []子 = []我 = 0而 i != len(s) - 1:当 s[i] s[i-1]:subs.append(s[i])我 += 1subs = ''.join(subs)ans.append(subs)子 = []打印答案

由于 i+1 测试超出了索引范围,因此字符串的最后一个字母一直有问题.我花了很长时间修补它,试图想出一种方法来避免这个问题.有人知道怎么做吗?

解决方案

为什么不将第一个字母硬编码到 ans 中,然后只处理字符串的其余部分?您可以只迭代字符串本身而不是使用索引.

<预><代码>>>>s = 'acegibdh'>>>答案 = []>>>ans.append(s[0])>>>对于 s[1:] 中的字母:...如果字母 >= ans[-1][-1]:... ans[-1] += 字母... 别的:... ans.append(信)...>>>回答['acegi', 'bdh']

I'm trying to write a function that takes a string s as an input and returns a list of those substrings within s that are alphabetical. For example, s = 'acegibdh' should return ['acegi', 'bdh'].

Here's the code I've come up with:

s = 'acegibdh'
ans = []
subs = []
i = 0
while i != len(s) - 1:
    while s[i] < s[i+1]:
        subs.append(s[i])
        i += 1
    if s[i] > s[i-1]:
        subs.append(s[i])
        i += 1
    subs = ''.join(subs)
    ans.append(subs)
    subs = []
print ans 

It keeps having trouble with the last letter of the string, because of the i+1 test going beyond the index range. I've spent a long time tinkering with it to try and come up with a way to avoid that problem. Does anyone know how to do this?

解决方案

Why not hard-code the first letter into ans, and then just work with the rest of the string? You can just iterate over the string itself instead of using indices.

>>> s = 'acegibdh'
>>> ans = []
>>> ans.append(s[0])
>>> for letter in s[1:]:
...     if letter >= ans[-1][-1]:
...             ans[-1] += letter
...     else:
...             ans.append(letter)
...
>>> ans
['acegi', 'bdh']

这篇关于如何返回按字母顺序排列的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆