classSolution: defreverseWords(self, s: str) -> str: from collections import deque left, right = 0, len(s) - 1
# 去除前导空格 while left <= right and s[left] == ' ': left += 1
# 去除尾随空格 while left <= right and s[right] == ' ': right -= 1 # q为双端队列,word用来储存单词 q, word = deque(), [] while left <= right: # 这样可以避免出现单词之间1个以上的空格 if s[left] == ' 'and word: q.appendleft(''.join(word)) word = [] elif s[left] != ' ': word.append(s[left]) left += 1 # 将剩余的单词添加进队列 q.appendleft(''.join(word)) return' '.join(q)
int left = 0, right = s.size() - 1; // 删除前导空格 while (left <= right && s[left] == ' ') ++left; // 删除尾随空格 while (left <= right && s[right] == ' ') --right;
deque<string> q; string word; while (left <= right) { char c = s[left]; // 避免单词之间出现1个以上的空格 if (word.size() && c == ' ') { q.push_front(move(word)); word = ""; } elseif (c != ' ') word += c; ++left; } q.push_front(move(word)); // c++没有join,所以要自己添加。 string ans; while (!q.empty()) { ans += q.front(); q.pop_front(); if (!q.empty()) ans += ' '; } return ans; } };