medium程度题
题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
难度在于给定字符串中空格连续出现的次数不限定
如Given s = " I love you 365 days ha ha ",
则return "ha ha days 365 you love I".
我的想法是把所有夹在空格之间的子串提取出来放在一个容器中,最后再相加。AC代码(效率不高):
class Solution
{
public:
void reverseWords(string &s)
{
do
{
if(s.empty())
break;
vector<string> vec_result;
int i = 0 , j = 0;
while(s[i] != '\0')
{
while(s[i] == ' ')
i++; //第一个不为空格的字符
j = i;
while(s[i] != ' '&&s[i] != '\0')
i++; //s[i]指向一个子串的尾部
if (i > j) //如果i>j 则i,j之间含有一个子串
{
string temp;
temp.assign(s,j,i - j);
vec_result.push_back(temp);
}
}
s.erase();
int size = vec_result.size();
if (size == 0)
break;
for (int m = size -1;m >= 1;m--) //把容器中的字符串相加......
s = s + vec_result[m] + " ";
s += vec_result[0];
}while(false);
}
};OMG,比较粗暴。

本文探讨了一道中等难度的编程题:给定一个字符串,按单词进行反转。文章提供了一个AC代码示例,虽然效率不高,但成功实现了题目要求的功能。
529

被折叠的 条评论
为什么被折叠?



