Reverse Words in a String

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

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

click to show clarification.blog

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.
思路:從頭日後掃描字符串,從第一個開始不是空格算起。將單詞放入temp中,直到遇到空格,做以下處理,將單詞放入result中去,接下來再有單詞能夠放到上一個單詞的前面,另加空格。如此反覆,就能夠將單詞與單詞爲單位反轉了。
class Solution {
public:
    void reverseWords(string &s) {
        int nLen=s.size();
        if(nLen<=0)
            return;
        string temp,result;
        int index=0;
        while(s[index]==' ')
            index++;
        for(int i=index;i<nLen;)
        {
            if(s[i]!=' ')
            {
                temp+=s[i];
                i++;
            }
            else
            {
                while(s[i]==' ')
                    i++;
                if(i==nLen)
                    break;
                result=" "+temp+result;
                temp="";
            }
        }
        s=temp+result;
    }
};
相關文章
相關標籤/搜索