经同学介绍这个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等高一些吧。