码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String II

时间:2016-09-22 13:00:59      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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 end
11             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

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5895643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!