且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否在python中按字母顺序排列

更新时间:2023-02-26 20:38:58

这具有O(n)的优势(将字符串排序为O(n log n)).如果Python中的一个字符(或字符串)以字母顺序出现在另一个字符之前,则它小于"另一个字符,因此,为了查看字符串是否以字母顺序排列,我们只需要比较每对相邻的字符即可.另外,请注意,您使用range(len(word)-1)而不是range(len(word)),因为否则,在循环的最后一次迭代中,您将越过字符串的边界.

This has the advantage of being O(n) (sorting a string is O(n log n)). A character (or string) in Python is "less than" another character if it comes before it in alphabetical order, so in order to see if a string is in alphabetical order we just need to compare each pair of adjacent characters. Also, note that you take range(len(word) - 1) instead of range(len(word)) because otherwise you will overstep the bounds of the string on the last iteration of the loop.

def isInAlphabeticalOrder(word):
    for i in range(len(word) - 1):
        if word[i] > word[i + 1]:
            return False
    return True