首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。