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".

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) {
        int i = 0, j = 0;
        int n = s.size();

        while(i < n){
            //跳过前面的空白符
            while(i < n && isspace(s[i]))
                i++;
            //全是空白符,直接跳出
            if(i == n)  break;
            //这个是为了解决将多个空格转成一个空格
            if(i > 0 && j > 0)
                s[j++] = ' ';

            int start = j;
            //将后面的单词移到前面的空格中
            while(i < n && !isspace(s[i])){
                s[j++] = s[i++];
            }
            reverse(s.begin() + start, s.begin() + j);
        }
        s.resize(j);
        reverse(s.begin(), s.end());
    }
};

results matching ""

    No results matching ""