PAT乙级1009

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805316250615808

题解一

我的方法如下:

  1. 将这一行字符串格式看做:第一个单词( 单词)( 单词)( 单词)
  2. 利用循环输出所有( 单词)
  3. 输出第一个单词
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
// PAT BasicLevel 1009
// https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960

#include <iostream>
#include <string>
using namespace std;

int main()
{
// 获取用户输入的一行
string str;
getline(cin,str); // 可读取空格,遇到换行停止,并不读取换行

// 将这一行字符串格式看做:第一个单词( 单词)( 单词)( 单词)
// 从右边找空格然后一直输出( 单词)
int indexOfSpace;
while ((indexOfSpace = str.find_last_of(" ")) != str.npos) //length()和size()是一样的
{
cout << str.substr(indexOfSpace + 1, str.length()) << ' ';
str=str.substr(0,indexOfSpace);
}

// 输出第一个单词
cout << str.substr(0,str.length());

//system("pause");
return 0;
}

题解二

这个方法也挺不错的,我很喜欢。

利用到了栈先进后出的特点,以及cin遇到空格和回车停止,不读取换行的特点。

参考链接:https://www.cnblogs.com/cdp1591652208/p/7138046.html

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
// PAT BasicLevel 1009
// https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main()
{
// 保存所有单词
stack<string> strs;

// 保存一个单词
string str;

// 读取所有单词
while(cin>> str){
strs.push(str);
if(getchar()=='\n')
break;
}

// 输出所有单词
cout << strs.top();
strs.pop();
while (!strs.empty()){
cout << ' ' << strs.top();
strs.pop();
}

//system("pause");
return 0;
}

作者:@臭咸鱼

转载请注明出处:https://chouxianyu.github.io

欢迎讨论和交流!