首页 > 代码库 > Reverse Words in a String

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

解决方案:

该题目解决思路很简单,新建一个字符串,然后对于给定字符串,从后向前遍历,遇到一个单词就加到新建的字符串中,别忘了加空格。当然提前还得去除给定字符串首尾的空白符号。下面是该题的代码:

 1 class Solution { 2 public: 3     void reverseWords(string &s) { 4         int i = 0; 5         int j = s.size() - 1; 6         string str; 7         for(; s[i] ==  ; ++i); 8         for(; s[j] ==  ; --j); 9 10         int temp;11         for(temp = j; temp >= i; --temp){12             if (s[temp] ==   && s[temp + 1] !=  ){13                 str.append(s, temp + 1, j - temp);14                 str.append(1,  );15             }16             if (s[temp] !=   && s[temp + 1] ==  ) {17                 j = temp;18             }19         }20         str.append(s, temp + 1, j - temp);21         s = str;22     }23 };

 

Reverse Words in a String