题目描述:
将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
接口说明
/*** 反转句子
*
* @param sentence 原句子
* @return 反转后的句子
*/
public String reverse(String sentence);
知识点: 数组
输入: 将一个英文语句以单词为单位逆序排放。
输出: 逆序的句子
样例输入: I am a boy
样例输出: boy a am I
思路:
首先将整个句子倒序;
再识别每个单词,并对每个单词进行倒序。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
int len = str.size(),i=0;
reverse(str.begin(), str.end());
// cout << str << endl;
while (i < len)
{
while (str[i] == ' '&&i<len)
i++;
// cout << "begin: " << i << " ";
int begin = i;
while (str[i] != ' '&&i<len)
i++;
int end = i-1;
// cout << "end: " << end << endl;
for (int j = begin; j <= (end+begin) / 2; j++)
{
char temp = str[j];
str[j] = str[begin+end-j];
str[begin + end - j] = temp;
}
}
cout << str << endl;
// system("pause");
return 0;
}
得分 | 运行时间 | 内存 | 复杂度 | 最大嵌套深度 |
100(100) | 16ms | 2044KB | 7 | 3 |