原题
https://leetcode.cn/problems/reverse-words-in-a-string/description/
思路
字符串处理
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def reverseWords(self, s: str) -> str:
s_list = reversed(s.strip().split())
return ' '.join(s_list)
Go代码
func reverseWords(s string) string {
words := []string{}
word := ""
for _, ch := range s {
if ch == ' ' {
if len(word) > 0 {
words = slices.Insert(words, 0, word)
word = ""
} else {
// 去掉前导空格、尾随空格或者单词间的多个空格
continue
}
} else {
word += string(ch)
}
}
if len(word) > 0 {
words = slices.Insert(words, 0, word)
}
return strings.Join(words, " ")
}
577

被折叠的 条评论
为什么被折叠?



