|
| 1 | +/** |
| 2 | + * [290] Word Pattern |
| 3 | + * |
| 4 | + * Given a pattern and a string str, find if str follows the same pattern. |
| 5 | + * |
| 6 | + * Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: pattern = "abba", str = "dog cat cat dog" |
| 12 | + * Output: true |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * |
| 17 | + * Input:pattern = "abba", str = "dog cat cat fish" |
| 18 | + * Output: false |
| 19 | + * |
| 20 | + * Example 3: |
| 21 | + * |
| 22 | + * |
| 23 | + * Input: pattern = "aaaa", str = "dog cat cat dog" |
| 24 | + * Output: false |
| 25 | + * |
| 26 | + * Example 4: |
| 27 | + * |
| 28 | + * |
| 29 | + * Input: pattern = "abba", str = "dog dog dog dog" |
| 30 | + * Output: false |
| 31 | + * |
| 32 | + * Notes:<br /> |
| 33 | + * You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space. |
| 34 | + * |
| 35 | + */ |
| 36 | +pub struct Solution {} |
| 37 | + |
| 38 | +// submission codes start here |
| 39 | + |
| 40 | +use std::collections::HashMap; |
| 41 | +impl Solution { |
| 42 | + pub fn word_pattern(pattern: String, s: String) -> bool { |
| 43 | + let mut p2s = HashMap::new(); |
| 44 | + let mut s2p = HashMap::new(); |
| 45 | + let mut s_iter = s.split(" "); |
| 46 | + let mut p_iter = pattern.chars(); |
| 47 | + loop { |
| 48 | + match (s_iter.next(), p_iter.next()) { |
| 49 | + (Some(sub), Some(ch)) => { |
| 50 | + if *p2s.entry(ch).or_insert(sub) != sub || |
| 51 | + *s2p.entry(sub).or_insert(ch) != ch { |
| 52 | + return false |
| 53 | + } |
| 54 | + }, |
| 55 | + (None, None) => break, |
| 56 | + _ => return false, |
| 57 | + } |
| 58 | + } |
| 59 | + true |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// submission codes end |
| 64 | + |
| 65 | +#[cfg(test)] |
| 66 | +mod tests { |
| 67 | + use super::*; |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn test_290() { |
| 71 | + assert_eq!(Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()), true); |
| 72 | + assert_eq!(Solution::word_pattern("aaaa".to_owned(), "dog cat cat dog".to_owned()), false); |
| 73 | + assert_eq!(Solution::word_pattern("abba".to_owned(), "dog cat cat fish".to_owned()), false); |
| 74 | + } |
| 75 | +} |
0 commit comments