151. Reverse Words in a String

description:

151 Reverse Words in a String      15.7% Medium

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

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

my solution:

class Solution {
public:
	void reverseWords(string &s) {
		vector<string> wordsContainer;
		int head = 0;
		int end = s.find_first_of(' ',head);
		int tempPoint;
		string temp;
		if (s.length() == 0)return;
		while (end != string::npos) {
			temp = s.substr(head, end - head);
			if (temp != " ")wordsContainer.push_back(temp);
			head = end;
			end = s.find_first_of(' ', head + 1);
		}
		temp = s.substr(head, end - head);
		if(temp != " ") wordsContainer.push_back(s.substr(head, end - head));
		if (wordsContainer.size() == 1)
		{
			s = wordsContainer[0];
			return;
		}
		wordsContainer.back().erase(0, 1);
		if (wordsContainer[0] != "")wordsContainer[0] = " " + wordsContainer[0];
		tempPoint = 0;
		s = "";
		for (int i = wordsContainer.size() - 1; i != -1;i--) {
			s += wordsContainer[i];
		}
	}
};

better ways:

by 

yuruofeifei 

void reverseWords(string &s) {
		reverse(s.begin(), s.end()); //反转整个数组
		int storeIndex = 0;
		for (int i = 0; i < s.size(); i++) {
			if (s[i] != ' ') {//找到首个不为空格的字符
				if (storeIndex != 0) s[storeIndex++] = ' ';//在某个word之后添加空格
				int j = i;
				while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; }//把word赋值到s
				reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);//反转word
				i = j;
			}
		}
		s.erase(s.begin() + storeIndex, s.end());//清除尾部的空格
	}

thought:

该题我一开始的想法是,分别从前向后和从后向前找到每个单词,再交换单词。但是在实施的过程中发现这个办法过于复杂了,而且字符串的长度是有可能变化的,所以行不通。后来决定,把字符串根据空格为界限,拆分成多个词,字符串变空,再按照倒序把词添加到字符串的末尾。想法很理想,但是实现的时候对空格的处理不太好,所以出现了很多bug,修修补补也算是通过了。

看到别人的方法,首先把整个字符串都反转,然后从头到尾找单词,把单词再反转回来,按顺序挪到串头,最后清除掉多余的部分,这种化零为整的处理办法,相对来说要简单很多。



yuruofeifei 

点赞