编写一个程序来颠倒给定句子中的单词顺序。单词被定义为非空格字符的序列。该句子是由空格分隔的单词的集合。
例子:
输入: “Hello World”
输出: “World Hello”
输入: “Programming is fun”
输出: “fun is Programming”
方法:要解决该问题,请遵循以下思路:
这个问题可以通过将句子拆分为单词来解决。将句子拆分为单词后,颠倒单词的顺序,然后通过在所有单词之间添加空格来重建句子。
分步算法:
- 使用空格作为分隔符将句子拆分为单词。
- 颠倒单词的顺序。
- 通过用空格连接颠倒的单词来重构句子。
下面是算法的实现:C++
include <bits/stdc++.h> using namespace std;
string reverseWords(string sentence) {
// vector to store the words vector<string> words; string word = "", reversedSentence = ""; for (int i = 0; i < sentence.length(); i++) { if (sentence[i] == ' ') { words.push_back(word); word = ""; } else { word += sentence[i]; } }
if (word != "") { words.push_back(word); }
// Append the words in reverse order for (int i = words.size() - 1; i >= 0; i--) { reversedSentence.append(words[i]); reversedSentence.append(" "); }
return reversedSentence; }
int main() { char sentence[] = "Programming is fun"; cout << reverseWords(sentence); return 0; }
|
C
include <stdio.h> include <string.h>
void reverseWords(char* sentence) { char* word = strtok(sentence, " "); char* words[100]; int count = 0;
while (word != NULL) { words[count++] = word; word = strtok(NULL, " "); }
for (int i = count - 1; i >= 0; --i) { printf("%s ", words[i]); } }
int main() { char sentence[] = "Programming is fun"; reverseWords(sentence); return 0; }
|
java
public class ReverseWords { public static void reverseWords(String sentence) { String[] words = sentence.split(" "); for (int i = words.length - 1; i >= 0; i--) { System.out.print(words[i] + " "); } }
public static void main(String[] args) { String sentence = "Programming is fun"; reverseWords(sentence); } }
|
Python3
def reverse_words(sentence): words = sentence.split() reversed_sentence = ' '.join(reversed(words)) print(reversed_sentence)
sentence = "Programming is fun" reverse_words(sentence)
|
C#
using System;
class Program { static void Main() { string sentence = "Programming is fun"; ReverseWords(sentence); }
static void ReverseWords(string sentence) { string[] words = sentence.Split(' '); Array.Reverse(words); Console.WriteLine(string.Join(" ", words)); } }
|
Javascript
function reverseWords(sentence) { // Split the sentence into an array of words const words = sentence.split(' ');
// Reverse the order of the words const reversedWords = words.reverse();
// Join the reversed words to form the reversed sentence const reversedSentence = reversedWords.join(' ');
return reversedSentence; }
const sentence = "Programming is fun"; console.log(reverseWords(sentence));
|
时间复杂性:O(N),其中 N 是句子的长度。
辅助空间:O(N),额外空间用于存储单词。