151. Reverse Words in a String

description:

151   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 

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,修修补补也算是通过了。

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值