LeetCode Reverse Words in a String Total

Reverse Words in a String Total 
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) 
    {
      vector <string> words;//保存摳出的單詞
	bool flag = 0;
	string w;
	for(int i = 0; i != s.size(); i++)
	{
		if(s[i] != ' ')
		{
			if(flag == 0)	flag = 1;
			w.push_back(s[i]);
		}
		else 
		{
			if(flag == 1)
			{
				words.push_back(w);
				w.clear();
				flag = 0;
			}
		}
	}
	if(flag == 1) words.push_back(w);//最後一個可能沒遇到空格就結束了
	s.clear();
	if(words.size())//排除只有空格的字符串或者空字符串
	{
		for(int i = words.size() - 1; i != 0; i--)
		{
			s = s + words[i] + ' ';
		}
		s = s + words[0];
	}
    }
};



發佈了62 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章