自学内容网 自学内容网

Study Plan For Algorithms - Part34

1. 翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
方法一:

def reverseWords(s):
    s = s.strip()
    i = len(s) - 1
    j = i
    res = []
    while i >= 0:
        while i >= 0 and s[i]!= " ":
            i -= 1
        res.append(s[i + 1:j + 1] + " ")
        while i >= 0 and s[i] == " ":
            i -= 1
        j = i
    return "".join(res).strip()

方法二:

def reverseWords(s):
    words = s.split()
    reversed_words = words[::-1]
    return " ".join(reversed_words)

方法三:

def reverseWords(s):
    parts = []
    word = ""
    for char in s:
        if char == " ":
            if word:
                parts.append(word)
                word = ""
        else:
            word += char
    if word:
        parts.append(word)
    return " ".join(reversed(parts))

原文地址:https://blog.csdn.net/qq_24058289/article/details/142373367

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!