comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
简单 |
|
给定一个字符串 s
,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = "Let's take LeetCode contest" 输出:"s'teL ekat edoCteeL tsetnoc"
示例 2:
输入: s = "Mr Ding" 输出:"rM gniD"
提示:
1 <= s.length <= 5 * 104
s
包含可打印的 ASCII 字符。s
不包含任何开头或结尾空格。s
里 至少 有一个词。s
中的所有单词都用一个空格隔开。
我们可以将字符串
时间复杂度
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(t[::-1] for t in s.split())
class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
for (int i = 0; i < words.length; ++i) {
words[i] = new StringBuilder(words[i]).reverse().toString();
}
return String.join(" ", words);
}
}
class Solution {
public:
string reverseWords(string s) {
stringstream ss(s);
string t;
string ans;
while (ss >> t) {
reverse(t.begin(), t.end());
ans += t;
ans.push_back(' ');
}
ans.pop_back();
return ans;
}
};
func reverseWords(s string) string {
words := strings.Fields(s)
for i, w := range words {
t := []byte(w)
slices.Reverse(t)
words[i] = string(t)
}
return strings.Join(words, " ")
}
function reverseWords(s: string): string {
return s
.split(' ')
.map(t => t.split('').reverse().join(''))
.join(' ');
}
impl Solution {
pub fn reverse_words(s: String) -> String {
s.split(' ')
.map(|s| s.chars().rev().collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
}
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function (s) {
return s
.split(' ')
.map(t => t.split('').reverse().join(''))
.join(' ');
};
class Solution {
/**
* @param String $s
* @return String
*/
function reverseWords($s) {
$words = explode(' ', $s);
foreach ($words as $i => $word) {
$words[$i] = strrev($word);
}
return implode(' ', $words);
}
}