使用字母字符串对列表排序

2024-04-26 00:04:28 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
1条回答
网友
1楼 · 发布于 2024-04-26 00:04:28

你在找桶型的。此处:

def sort_char_list(lst):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    # Here, create the 26 buckets
    new_list = [''] * len(alphabet)

    for letter in lst:
        # This is the bucket index
        # You could use `ord(letter) - ord('a')` in this specific case, but it is not mandatory
        index = alphabet.index(letter)
        new_list[index] += letter

    # Assemble the buckets
    return ''.join(new_list)

至于复杂性,由于alphabet是一个预定义的固定大小字符串,因此在其中搜索一个字母最多需要26个操作,即O(1)。因此,总体复杂性是O(n)

相关问题 更多 >