Study Plan For Algorithms - Part34
1. 翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
方法一:
def reverseWords(s):s = s.strip()i = len(s) - 1j = ires = []while i >= 0:while i >= 0 and s[i]!= " ":i -= 1res.append(s[i + 1:j + 1] + " ")while i >= 0 and s[i] == " ":i -= 1j = ireturn "".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 += charif word:parts.append(word)return " ".join(reversed(parts))