0%

翻转单词顺序列

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

全翻转,再翻转单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
void swap(string &text, const int a, const int b)
{
int x = a, y = b - 1;
while (x < y)
{
char temp = text[x];
text[x] = text[y];
text[y] = temp;
x++;
y--;
}
}
string ReverseSentence(string str) {
const int l = str.length();
int a = 0;
for (int i = 0; i < l; i++)
{
if (str[i] == ' ')
{
swap(str, a, i);
a = i + 1;
}
else if (i == l - 1)
{
swap(str, a, i + 1);
a = i + 1;
}
}
if (a != 0)
{
swap(str, 0, l);
}
return str;
}
};