#include <iostream>
#include <string>
using namespace std;
/*
翻转句子: 例如输入: i am a student;
输出: student; a am i
*/
class Solution {
public:
string ReverseSentence(string str) {
int tmp = str.size();
string verword;
//从后向前遍历,遇到空格,表示过了一个单词,将该单词保存
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == ' ') {
for (int j = i + 1; j < tmp; j++)
{
verword.push_back(str[j]);
}
tmp = i;
verword.push_back(str[i]);
}
}
for (int j = 0; j < tmp; j++)
{
verword.push_back(str[j]);
}
return verword;
}
};
int main()
{
string word;
char s;
while (1)
{
s = getchar();
if (s == '\n') {
break;
}
word.push_back(s);
}
Solution a;
cout << a.ReverseSentence(word) << endl;
return 0;
}
例如输入: i am a student; 输出: student; a am i
最新推荐文章于 2021-07-02 17:34:24 发布