首页 > 代码库 > Reverse Words in a String II

Reverse Words in a String II

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?

Related problem: Rotate Array

 

Runtime: 6ms

 1 class Solution { 2 public: 3     void reverseWords(string &s) { 4         // reverse the entire string 5         reverseString(s, 0, s.size() - 1); 6          7         // reverse each single word 8         for (int i = 0; i < s.size(); ) { 9             int wordEndNext = s.find(" ", i);10             // reach to end11             if (wordEndNext == s.npos) { 12                 reverseString(s, i, s.size() - 1);13                 return;14             } else {15                 reverseString(s, i, wordEndNext - 1);16                 i = wordEndNext + 1;17             }18         }19     }20     21     void reverseString(string &s, int begin, int end) {22         for (int i = begin, j = end; i < j; i++, j--)23             swap(s[i], s[j]);24     }25 };

 

Reverse Words in a String II