首页 > 其他 > 详细

Reverse Words in a String II

时间:2016-09-22 12:59:12      阅读:162      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!