解题思路

  1. 读取输入的句子
  2. 将句子按空格分割成单词列表
  3. 反转单词列表
  4. 将反转后的单词列表重新组合成字符串
  5. 输出结果

代码

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    string line;
    getline(cin, line);
    
    istringstream iss(line);
    vector<string> words;
    string word;
    
    // 分割单词
    while (iss >> word) {
        words.push_back(word);
    }
    
    // 反转单词列表
    reverse(words.begin(), words.end());
    
    // 输出结果
    for (size_t i = 0; i < words.size(); ++i) {
        if (i > 0) cout << " ";
        cout << words[i];
    }
    cout << endl;
    
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        
        // 分割单词
        String[] words = line.split(" ");
        
        // 反转单词列表
        Collections.reverse(Arrays.asList(words));
        
        // 输出结果
        System.out.println(String.join(" ", words));
    }
}
# 读取输入
s = input()

# 分割单词并反转
words = s.split()
words.reverse()

# 输出结果
print(" ".join(words))

算法及复杂度

  • 算法:字符串分割、列表反转、字符串拼接
  • 时间复杂度: - 其中为字符串长度
  • 空间复杂度: - 需要存储分割后的单词列表