[LeetCode] Reverse Words in a String

来源:互联网 发布:淘宝免费活动大全 编辑:程序博客网 时间:2024/06/05 13:14
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.

代码很简单:

从头向尾扫描s:

如果当前字符是space,而且buffer string 不为空,那么输出buffer string。

如果当前字符是space,而且buffer string为空,那么不输出buffer string。

如果当前字符不是space,那么把当前字符添加到buffer string。

class Solution {public:    void reverseWords(string &s) {        string word; //tmp string to store each word        string res; // result string        int i=0;        while (i<s.size()){            if (char(s[i])==' ' && word.empty()){i++;continue;} //multiple spaces            if (char(s[i])==' ' && !word.empty()){ //first space after a word                res = word+" "+ res; //store the word                word=""; //reset the word                i++; continue;            }            if (char(s[i])!=' '){word=word+char(s[i]);i++; continue;} //non-space chars         }                if (!word.empty()){ //last word            s = word+" "+res;        }else{            s = res;        }        s = s.substr(0,s.size()-1); //eliminate the last space    }    };



0 0
原创粉丝点击