diff --git a/src/leetcode/0151.reverse-words-in-a-string/Cargo.toml b/src/leetcode/0151.reverse-words-in-a-string/Cargo.toml new file mode 100644 index 00000000..402da23b --- /dev/null +++ b/src/leetcode/0151.reverse-words-in-a-string/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0151-reverse-words-in-a-string" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/src/leetcode/0151.reverse-words-in-a-string/index.md b/src/leetcode/0151.reverse-words-in-a-string/index.md new file mode 100644 index 00000000..77a618ba --- /dev/null +++ b/src/leetcode/0151.reverse-words-in-a-string/index.md @@ -0,0 +1,4 @@ + +# + +[问题描述](../problems/) diff --git a/src/leetcode/0151.reverse-words-in-a-string/src/main.rs b/src/leetcode/0151.reverse-words-in-a-string/src/main.rs new file mode 100644 index 00000000..74fcd2b2 --- /dev/null +++ b/src/leetcode/0151.reverse-words-in-a-string/src/main.rs @@ -0,0 +1,71 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +// 使用 str::split_ascii_whitespace(). +pub fn reverse_words1(s: String) -> String { + let parts: Vec<&str> = s.split_ascii_whitespace().rev().collect(); + parts.join(" ") +} + +// 手动实现空格的分隔操作 +pub fn reverse_words2(s: String) -> String { + debug_assert!(!s.is_empty()); + + let mut index: usize = 0; + let bytes: &[u8] = s.as_bytes(); + let len: usize = bytes.len(); + let mut parts: Vec<&str> = Vec::new(); + + while index < len { + if bytes[index] != b' ' { + // 贪心, 读取尽可能多的字符. + let start: usize = index; + while index < len && bytes[index] != b' ' { + index += 1; + } + parts.push(&s[start..index]); + } + + index += 1; + } + + parts.reverse(); + parts.join(" ") +} + +pub type SolutionFn = fn(String) -> String; + +fn check_solution(func: SolutionFn) { + let s = "the sky is blue".to_owned(); + let exp = "blue is sky the".to_owned(); + assert_eq!(func(s), exp); + + let s = " hello world ".to_owned(); + let exp = "world hello".to_owned(); + assert_eq!(func(s), exp); + + let s = "a good example".to_owned(); + let exp = "example good a".to_owned(); + assert_eq!(func(s), exp); +} + +fn main() { + check_solution(reverse_words1); + check_solution(reverse_words2); +} + +#[cfg(test)] +mod tests { + use super::{check_solution, reverse_words1, reverse_words2}; + + #[test] + fn test_reverse_words1() { + check_solution(reverse_words1); + } + + #[test] + fn test_reverse_words2() { + check_solution(reverse_words2); + } +}