aboutsummaryrefslogtreecommitdiff
path: root/reverse_word_string.rs
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /reverse_word_string.rs
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'reverse_word_string.rs')
-rw-r--r--reverse_word_string.rs31
1 files changed, 31 insertions, 0 deletions
diff --git a/reverse_word_string.rs b/reverse_word_string.rs
new file mode 100644
index 0000000..6acc9a4
--- /dev/null
+++ b/reverse_word_string.rs
@@ -0,0 +1,31 @@
+struct Solution;
+
+impl Solution {
+ pub fn reverse_words(s: String) -> String {
+ let mut s: Vec<char> = s.trim().chars().rev().collect();
+ s.push(' ');
+ let mut i: usize = 0;
+ for j in 0..s.len() {
+ if s[j] == ' ' {
+ s[i..j].reverse();
+ i = j + 1;
+ }
+ }
+ s.pop();
+ let mut i = 1;
+ for j in 1..s.len() {
+ if s[j] == ' ' && s[j - 1] == ' ' {
+ continue;
+ }
+ s[i] = s[j];
+ i += 1;
+ }
+ s.truncate(i);
+ s.into_iter().collect()
+ }
+}
+
+fn main() {
+ let s = "the sky is blue".to_string();
+ print!("{}", Solution::reverse_words(s));
+}