leetcode - Reverse Words in a String

leetcode - Reverse Words in a String

 

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
class Solution {
public:
    void reverseWords(string &s) {
        reverse(s.begin(), s.end()); //reverse the whole string.
        string::iterator it = s.begin();
        while(it!=s.end()){
            while(it != s.end() && *it==' '){
                if(*(it+1)==' '){ it = s.erase(it);}
//if the next one is space, erase the current one.
// erase will return the next iterator.
else{it++;} // else it++ } string::iterator beg = it; while(it != s.end() && *it!=' '){ it++; } string::iterator end = it; reverse(beg,end); // reverse each words. } if(*(s.begin()) == ' ') s.erase(s.begin()); // remove the first space if(*(s.end()-1) == ' ') s.erase(s.end()-1); // remove the last space. } };

剑指offer面试题42.

先将整个字符串转置,然后对其中每个词转置。

注意使用erase用法,输入待删除的迭代器,返回的是后面第一个有效的迭代器,之前的后面的迭代器都失效。

注意reverse的用法,输入的是迭代器区间,包括第一个,不包括最后一个(前闭后开区间)。

注意处理多个空格的情况,遍历完后保证只有一个空格,然后清除头尾剩余的空格(如果有的话)。

整个算法in-place.

posted @ 2015-08-16 11:51  cnblogshnj  阅读(142)  评论(0)    收藏  举报