151. Reverse Words in a String Medium

@problem@discussion
#Two Pointers#String



1/**
2 * [151] Reverse Words in a String
3 *
4 * Given an input string s, reverse the order of the words.
5 * A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
6 * Return a string of the words in reverse order concatenated by a single space.
7 * Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
8 *  
9 * Example 1:
10 * 
11 * Input: s = "the sky is blue"
12 * Output: "blue is sky the"
13 * 
14 * Example 2:
15 * 
16 * Input: s = "  hello world  "
17 * Output: "world hello"
18 * Explanation: Your reversed string should not contain leading or trailing spaces.
19 * 
20 * Example 3:
21 * 
22 * Input: s = "a good   example"
23 * Output: "example good a"
24 * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
25 * 
26 *  
27 * Constraints:
28 * 
29 * 1 <= s.length <= 10^4
30 * s contains English letters (upper-case and lower-case), digits, and spaces ' '.
31 * There is at least one word in s.
32 * 
33 *  
34 * <b data-stringify-type="bold">Follow-up: If the string data type is mutable in your language, can you solve it <b data-stringify-type="bold">in-place with <code data-stringify-type="code">O(1) extra space?
35 * 
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/reverse-words-in-a-string/
40// discuss: https://leetcode.com/problems/reverse-words-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45    pub fn reverse_words(s: String) -> String {
46        let mut res = String::with_capacity(s.len());
47        for word in s.split_ascii_whitespace().rev() {
48            res = res + word + " ";
49        }
50        res.trim_end().to_string()
51    }
52}
53
54// submission codes end
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn test_151() {
62        assert_eq!(Solution::reverse_words("a good   example".to_string()), "example good a".to_string());
63    }
64}
65


Back
© 2025 bowen.ge All Rights Reserved.