Skip to content

Commit

Permalink
Added word pattern solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 28, 2024
1 parent 20b5b1c commit b6b6ebd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ programming challenges completed in other languages.
- [Count Negative Numbers](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix)
- [Guess Number](https://leetcode.com/problems/guess-number-higher-or-lower/)
- [Ransom Note](https://leetcode.com/problems/ransom-note)
- [Word Pattern](https://leetcode.com/problems/word-pattern)

#### Medium

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ mod unguarded_cells;
mod unique_occurrences;
mod valid_parenthesis;
mod valid_sudoku;
mod word_pattern;
mod x_kind;
mod xor_subarray;
mod zero_or_one;
Expand Down
37 changes: 37 additions & 0 deletions src/leetcode/word_pattern.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::collections::HashMap;

pub fn word_pattern(pattern: String, s: String) -> bool {
let words: Vec<_> = s.split_whitespace().map(String::from).collect();
if pattern.len() != words.len() {
return false;
}

let pattern = pattern.as_bytes();
let mut map = HashMap::new();
for (i, word) in words.into_iter().enumerate() {
if map.insert(pattern[i].to_string(), i) != map.insert(word, i) {
return false;
}
}
true
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test() {
assert!(word_pattern("aaa".to_string(), "dog dog dog".to_string()))
}

#[test]
fn test_name() {
assert!(!word_pattern("aaa".to_string(), "dog cat dog".to_string()));
assert!(!word_pattern(
"abba".to_string(),
"dog dog dog dog".to_string()
));
assert!(!word_pattern("aaa".to_string(), "aa aa aa aa".to_string()))
}
}

0 comments on commit b6b6ebd

Please sign in to comment.