Description#
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
1 <= s.length <= 5 * 104
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.- There is at least one word in
s
. - All the words in
s
are separated by a single space.
Solutions#
Solution 1#
1
2
3
| class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join([t[::-1] for t in s.split(' ')])
|
1
2
3
4
5
6
7
8
9
10
11
12
| class Solution {
public String reverseWords(String s) {
StringBuilder res = new StringBuilder();
for (String t : s.split(" ")) {
for (int i = t.length() - 1; i >= 0; --i) {
res.append(t.charAt(i));
}
res.append(" ");
}
return res.substring(0, res.length() - 1);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Solution {
public:
string reverseWords(string s) {
for (int i = 0, n = s.size(); i < n; ++i) {
int j = i;
while (++j < n && s[j] != ' ')
;
reverse(s.begin() + i, s.begin() + j);
i = j;
}
return s;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| func reverseWords(s string) string {
t := []byte(s)
for i := 0; i < len(t); i++ {
j := i
for j < len(t) && t[j] != ' ' {
j++
}
for st, ed := i, j-1; st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
}
i = j
}
return string(t)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
| function reverseWords(s: string): string {
return s
.split(/\s+/)
.map(str => {
let res = '';
for (const c of str) {
res = c + res;
}
return res;
})
.join(' ');
}
|
1
2
3
4
5
6
7
8
| impl Solution {
pub fn reverse_words(s: String) -> String {
s.split(' ')
.map(|s| s.chars().rev().collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Solution {
/**
* @param String $s
* @return String
*/
function reverseWords($s) {
$sArr = explode(' ', $s);
for ($i = 0; $i < count($sArr); $i++) {
$sArr[$i] = strrev($sArr[$i]);
}
return implode(' ', $sArr);
}
}
|