NowCode:HJ31 单词倒排

题目:单词倒排

对于给定的若干个单词组成的句子,每个单词均由大小写字母构成,单词间使用非字母字符分隔。输出以单词为单位逆序排放的结果,即仅逆序单词间的相对顺序,不改变单词内部的字母顺序。
特别地,在输出结果中,去除原有的分隔符,转而使用单个空格间隔单词。

输入描述:

在一行上输入若干个字符串,每个字符串长度为 1≦length(s)≦201≦length(s)≦20 ,仅由大小写字母构成,代表一个单词。单词间还夹杂了一定数量的非字母字符(但保证是可见字符),代表分隔符。

除此之外,保证总字符长度不超过 104104 。

输出描述:

在一行上输出一个句子,代表以单词为单位逆序排放的结果。单词间使用单个空格分隔。

示例1

1
2
3
4
5
输入:
Nowcoder Hello

输出:
Hello Nowcoder
示例2
1
2
3
4
5
输入:
$bo*y gi!r#l

输出:
l r gi y bo

题解1

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
#include <iostream>
#include <string>
using namespace std;

int main() {
std::string input;
getline(cin, input);
input = ' ' + input;
int nowIndex = 0;
for (int i = input.size() - 1; i >= 0; i--) {
// 找单词的尾巴
if (!(input[i] >= 'A' && input[i] <= 'Z') && !(input[i] >= 'a' && input[i] <= 'z')) {
continue;
}
// 找单词的头
nowIndex = i - 1;
while (nowIndex >= 0) {
if (!(input[nowIndex] >= 'A' && input[nowIndex] <= 'Z') && !(input[nowIndex] >= 'a' && input[nowIndex] <= 'z')) {
// 截取
cout << input.substr(nowIndex + 1, i - nowIndex) << " ";
i = nowIndex + 1;
break;
}
--nowIndex;
}
}

}
// 64 位输出请用 printf("%lld")

题解1

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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
std::string input;
getline(cin, input);
input += " ";
std::vector<std::string> vec;
for (int i = 0; i < input.size(); i++) {
if ((input[i] >= 'a' && input[i] <= 'z') || ((input[i] >= 'A') && input[i] <= 'Z')) {
for (int second = i + 1; second < input.size(); second++) {
if (!(input[second] >= 'a' && input[second] <= 'z') && !((input[second] >= 'A') && input[second] <= 'Z')) {
vec.push_back(input.substr(i, second - i));
i = second;
break;
}
}
}
}
for (auto it = vec.rbegin(); it != vec.rend(); it++) {
cout << *it << " ";
}
}
// 64 位输出请用 printf("%lld")

思路

题解1倒序遍历,双指针截取单词

题解2正序遍历,双指针截取单词

注意:当在for循环使用size_t i 时,注意当 i = 0时, i–后,i 不小于 0

for 循环嵌套时注意 break、continue