|
| 1 | +/** |
| 2 | + * [151] Reverse Words in a String |
| 3 | + * |
| 4 | + * Given an input string, reverse the string word by word. |
| 5 | + * |
| 6 | + * |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: "the sky is blue" |
| 12 | + * Output: "blue is sky the" |
| 13 | + * |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * |
| 18 | + * Input: " hello world! " |
| 19 | + * Output: "world! hello" |
| 20 | + * Explanation: Your reversed string should not contain leading or trailing spaces. |
| 21 | + * |
| 22 | + * |
| 23 | + * Example 3: |
| 24 | + * |
| 25 | + * |
| 26 | + * Input: "a good example" |
| 27 | + * Output: "example good a" |
| 28 | + * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. |
| 29 | + * |
| 30 | + * |
| 31 | + * |
| 32 | + * |
| 33 | + * Note: |
| 34 | + * |
| 35 | + * |
| 36 | + * A word is defined as a sequence of non-space characters. |
| 37 | + * Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. |
| 38 | + * You need to reduce multiple spaces between two words to a single space in the reversed string. |
| 39 | + * |
| 40 | + * |
| 41 | + * |
| 42 | + * |
| 43 | + * Follow up: |
| 44 | + * |
| 45 | + * For C programmers, try to solve it in-place in O(1) extra space. |
| 46 | + */ |
| 47 | +pub struct Solution {} |
| 48 | + |
| 49 | +// submission codes start here |
| 50 | + |
| 51 | +impl Solution { |
| 52 | + pub fn reverse_words(mut s: String) -> String { |
| 53 | + let mut seq = s.trim().chars().collect::<Vec<_>>(); |
| 54 | + seq.reverse(); |
| 55 | + let mut start_idx = 0_usize; |
| 56 | + let mut i = 0_usize; |
| 57 | + while i < seq.len() { |
| 58 | + if seq[i] == ' ' { |
| 59 | + if i == start_idx { |
| 60 | + seq.remove(i); |
| 61 | + continue; |
| 62 | + } |
| 63 | + seq[start_idx..i].reverse(); |
| 64 | + start_idx = i + 1; |
| 65 | + } |
| 66 | + i += 1; |
| 67 | + } |
| 68 | + seq[start_idx..].reverse(); |
| 69 | + seq.into_iter().collect() |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// submission codes end |
| 74 | + |
| 75 | +#[cfg(test)] |
| 76 | +mod tests { |
| 77 | + use super::*; |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn test_151() { |
| 81 | + assert_eq!(Solution::reverse_words("the sky is blue".to_owned()), "blue is sky the".to_owned()); |
| 82 | + assert_eq!(Solution::reverse_words(" hello world! ".to_owned()), "world! hello".to_owned()); |
| 83 | + } |
| 84 | +} |
0 commit comments