版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/83216215
我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960
题目描述:
知识点:字符串读取
思路:读入所有字符串进一个集合,再倒序输出
对于C++而言,可以用getchar() == '\n'来判断是否已经全部输入完毕。
而对于Java而言,可以读取整行数据再用split函数分段得到每一个字符串。
时间复杂度和空间复杂度均是O(n),其中n为输入字符串个数。
C++代码:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
string temp;
vector<string> strings;
while (true) {
cin >> temp;
strings.push_back(temp);
if (getchar() == '\n') {
break;
}
}
for (int i = strings.size() - 1; i >= 0; i--) {
cout << strings[i];
if (i != 0) {
cout << " ";
}
}
}
C++解题报告:
JAVA代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] strings = input.split(" ");
for (int i = strings.length - 1; i >= 0; i--) {
System.out.print(strings[i]);
if(i != 0){
System.out.print(" ");
}
}
}
}
JAVA解题报告: