...

面试题-单词分割及排序

题目

Sort a list of words based on number of characters
and ignore the asterisk separator between them

Example Input:
This*is*a***Hello**World***example**to*demo*your****coding*ability“

Example Output:
a is to This demo your Hello World coding ability example

参考实现

import re
from typing import List

SEP = re.compile('\*+')


def split_words(string: str) -> List[str]:
    return re.split(SEP, string)


def sort_words(words: List[str]) -> List[str]:
    if len(words) < 2:
        return words
    p = words[0]
    longer = []
    shorter = []
    same_length = [p]

    for word in words[1:]:
        if len(word) > len(p):
            longer.append(word)
        elif len(word) < len(p):
            shorter.append(word)
        else:
            same_length.append(word)

    return sort_words(shorter) + sorted(same_length, key=lambda word: word) + sort_words(longer)


def solution(string: str) -> str:
    words = split_words(string)
    sorted_words = sort_words(words)
    return ' '.join(sorted_words)


if __name__ == '__main__':
    r = solution('This*is*a***Hello**World***example**to*demo*your****coding*ability')
    print(r)
    assert r == 'a is to This demo your Hello World coding ability example'
posted @ 2024-10-29 22:44  韩志超  阅读(10)  评论(0编辑  收藏  举报