[LeetCode] Reverse Words in a String II 翻轉字串中的單詞之二
阿新 • • 發佈:2018-12-27
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
這道題讓我們翻轉一個字串中的單詞,跟之前那題Reverse Words in a String沒有區別,由於之前那道題我們就是用in-place的方法做的,而這道題反而更簡化了題目,因為不考慮首尾空格了和單詞之間的多空格了,方法還是很簡單,先把每個單詞翻轉一遍,再把整個字串翻轉一遍,或者也可以調換個順序,先翻轉整個字串,再翻轉每個單詞,參見程式碼如下:
class Solution { public: void reverseWords(string &s) { int left = 0; for (int i = 0; i <= s.size(); ++i) {if (i == s.size() || s[i] == ' ') { reverse(s, left, i - 1); left = i + 1; } } reverse(s, 0, s.size() - 1); } void reverse(string &s, int left, int right) { while (left < right) { char t = s[left]; s[left]= s[right]; s[right] = t; ++left; --right; } } };
類似題目: