20240507 Finished

This commit is contained in:
jackfiled 2024-05-07 14:18:09 +08:00
parent 123c111329
commit 3bf98430fc
2 changed files with 51 additions and 1 deletions

View File

@ -122,4 +122,5 @@ mod p54_spiral_matrix;
mod p48_rotate_image;
mod p73_set_matrix_zeroes;
mod p289_game_of_life;
mod p383_ransom_note;
mod p383_ransom_note;
mod p290_word_pattern;

View File

@ -0,0 +1,49 @@
/**
* [290] Word Pattern
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
impl Solution {
pub fn word_pattern(pattern: String, s: String) -> bool {
let words: Vec<&str> = s.split(' ').collect();
if words.len() != pattern.len() {
return false;
}
let mut map = HashMap::new();
let mut reverse_map = HashMap::new();
for (c, word) in pattern.chars().zip(words) {
let entry = map.entry(c).or_insert(word);
if *entry != word {
return false;
}
let entry = reverse_map.entry(word).or_insert(c);
if *entry != c {
return false;
}
}
true
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_290() {
assert!(Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()));
}
}