解题思路
- 首先将输入字符串中的非字母字符替换为空格
- 按空格分割字符串得到单词数组
- 反转单词数组
- 用空格连接单词数组输出结果
代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
getline(cin, s);
// 将非字母字符替换为空格
for(char& c : s) {
if(!isalpha(c)) {
c = ' ';
}
}
// 分割单词
vector<string> words;
string word;
for(int i = 0; i < s.length(); i++) {
if(s[i] != ' ') {
word += s[i];
} else if(!word.empty()) {
words.push_back(word);
word = "";
}
}
if(!word.empty()) {
words.push_back(word);
}
// 反转单词顺序
reverse(words.begin(), words.end());
// 输出结果
for(int i = 0; i < words.size(); i++) {
cout << words[i];
if(i != words.size() - 1) {
cout << " ";
}
}
return 0;
}
def word_reverse():
# 读取输入
s = input()
# 将非字母字符替换为空格
s = ''.join(' ' if not c.isalpha() else c for c in s)
# 分割并反转单词
words = s.split()
words.reverse()
# 输出结果
print(' '.join(words))
if __name__ == "__main__":
word_reverse()
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
// 将非字母字符替换为空格
s = s.replaceAll("[^a-zA-Z]", " ");
// 分割单词并反转
String[] words = s.trim().split("\\s+");
StringBuilder result = new StringBuilder();
// 倒序拼接单词
for(int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if(i > 0) {
result.append(" ");
}
}
System.out.println(result.toString());
}
}
算法及复杂度
- 算法:字符串处理 + 数组反转
- 时间复杂度:
,其中 n 为输入字符串长度
- 空间复杂度:
,需要存储分割后的单词数组