catalogue: string-分割
Question
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
class Solution {
public:
void reverseWords(string &s) {
string ret = "";
int pos=s.find_first_of(' ');
while (pos != s.npos)
{
ret = s.substr(0,pos) + " "+ ret;
pos=s.find(' ');
}
s = ret.substr(0,ret.length()-2);
}
};
Result:Time Limit Exceeded
Last executed input: " "
Second try
注意string为空的情况
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
string ret = "";
int pos=s.find_first_of(' ');
while (pos != s.npos)
{
ret = s.substr(0,pos) + " "+ ret;
pos=s.find(' ');
}
s = ret.substr(0,ret.length()-2);
}
};
Result:
Time Limit Exceeded
Last executed input: " "
Third try:
考虑多余的空格
class Solution {
public:
void reverseWords(string &s) {
s.erase( 0, s.find_first_not_of (' '));
s.erase( 0, s.find_last_not_of (' '));
if(s.empty()) return;
string ret = "";
int pos=s.find_first_of(' ');
while (pos != s.npos)
{
s = s.substr(0,pos);
s.erase( 0, s.find_first_not_of (' '));
ret = s + " "+ ret;
pos=s.find(' ');
}
s = ret.substr(0,ret.length()-2);
}
};
Result:Wrong
Input: "a"
Output: ""
Expected: "a"
Fourth try
处理最后
class Solution {
public:
void reverseWords(string &s) {
s.erase( 0, s.find_first_not_of (' '));
if(s.empty()) return;
string ret = "";
string tmp;
int pos=s.find_first_of(' ');
while (pos != s.npos)
{
tmp = s.substr(0, pos);
ret = tmp + " "+ ret;
s = s.substr(pos, s.length() - pos);
s.erase( 0, s.find_first_not_of (' '));
pos=s.find(' ');
}
s.erase( 0, s.find_last_not_of(' '));
ret = s + " "+ ret;
s = ret.substr(0,ret.length()-1);
}
};
Result: Wrong
Input: "1 "
Output: " 1"
Expected: "1"
Fifth try
处理最后是空格的情况
class Solution {
public:
void reverseWords(string &s) {
s.erase( 0, s.find_first_not_of (' '));
if(s.empty()) return;
string ret = "";
string tmp;
int pos=s.find_first_of(' ');
while (pos != s.npos)
{
tmp = s.substr(0, pos);
if(ret.empty()) ret = tmp;
else ret = tmp + " "+ ret;
s = s.substr(pos+1, s.length() - pos-1);
s.erase( 0, s.find_first_not_of (' '));
pos=s.find(' ');
}
s.erase( s.find_last_not_of(' ')+1);
if(!s.empty() && !ret.empty()) s = s + " "+ ret;
else if(!ret.empty()) s = ret;
}
};