王廷瑋|數位醫療|智慧醫療: 151. Reverse Words in a String WFU

2024年7月7日 星期日

151. Reverse Words in a String

151. Reverse Words in a String


給定一個輸入字符串 s,反轉單詞的順序。

單詞被定義為一個非空格字符的序列。字符串 s 中的單詞將由至少一個空格分隔。

返回一個單詞以單個空格連接的反轉順序的字符串。

注意,字符串 s 可能包含前導或尾隨空格或兩個單詞之間的多個空格。返回的字符串應只有一個空格分隔單詞。不要包含任何額外的空格。

範例 :

輸入: s = "the sky is blue" 輸出: "blue is sky the"


Python


class Solution:
def reverseWords(self, s: str) -> str:
# Split the string by spaces to get the words
words = s.split()
# Reverse the list of words
words.reverse()
# Join the reversed list of words with a single space
return ' '.join(words)

16.66MB, 31ms


C++


#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
string reverseWords(string s) {
// Split the string into words
vector<string> words;
string word;
istringstream stream(s);
while (stream >> word) {
words.push_back(word);
}
// Reverse the list of words
reverse(words.begin(), words.end());
// Join the reversed list of words with a single space
ostringstream result;
for (size_t i = 0; i < words.size(); ++i) {
if (i > 0) {
result << " ";
}
result << words[i];
}
return result.str();
}
};

10.54MB, 14ms


Javascript


/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
// Split the string by spaces to get the words
const words = s.trim().split(/\s+/);
// Reverse the list of words
words.reverse();
// Join the reversed list of words with a single space
return words.join(' ');
};

50.96MB, 76ms