LeetCode---Reverse Words in a String

经同学介绍这个OJ,拿过来练练手。

第一题 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".

乍一看,挺简单嘛,结果出现了各种纠结的问题,提交了以后给出Wrong Answer

怎么看自己的程序也是没问题的啊,然后继续看题,结果看漏了竟然还有点开的一段。

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.
原来,这个字符串可以为空(这个考虑到了)

字符串的首位的空格要过滤掉(这个没注意)

字符串中出现多个空格只保留一个(这个也没注意)

悲剧,工作一年多了,还是这么粗心大意,看题的时候没弄清楚就写,导致出现各种问题。往小说只是一个题目,往大了说如果这就是自己开发中某个项目里的客户需求,结果自己没有认真去分析,导致出现各种不可预知的结果。(哎,面壁思过几分钟)

这是我写的这个题目的代码(已AC):

class Solution {
public:
	void reverseWords(string &s) {
		if (s.size() <= 0)
		{
			return;
		}
		vector<string> vcstr;
		vcstr.clear();
		int prepos = 0;
		for (int i = 0; i < s.size(); i++)
		{
			if (s[prepos] == ' ')
			{
				prepos = i+1;
				continue;
			}
			if (s[i] == ' ')
			{
				string temstr = "";
				for (int j = prepos; j < i; j++)
				{
					temstr += s[j];
				}
				prepos = i+1;
				vcstr.push_back(temstr);
			}
			if (i == (s.size() - 1) && s[i] != ' ')
			{
				string temstr = "";
				for (int j = prepos; j <= i; j++)
				{
					temstr += s[j];
				}
				prepos = i+1;
				vcstr.push_back(temstr);
			}
		}
		string sstr = "";
		for (int i = vcstr.size() - 1; i >= 0; i--)
		{
			if (i != 0)
			{
				sstr += vcstr[i];
				sstr += " ";
			}
			else
			{
				sstr += vcstr[i];
			}
		}

		s = sstr;
	}
};


代码里应该有很多需要优化的东西,其实以前用C语言写过类似的函数,可以用两次翻转来实现,估计效率应该会比直接使用vector string等高一些吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值