leetcode_rust/
isomorphic_strings.rs1#![allow(dead_code)]
2
3pub fn is_isomorphic(s: String, t: String) -> bool {
5 use std::collections::HashMap;
6 let mut map: HashMap<u8, u8> = HashMap::new();
7 let mut map2: HashMap<u8, u8> = HashMap::new();
8 let s = s.into_bytes();
9 let t = t.into_bytes();
10 for i in 0..s.len() {
11 let c1 = s[i];
12 let c2 = t[i];
13
14 if map.contains_key(&c1) {
15 let v = map.get_mut(&c1).unwrap();
16 if *v != c2 {
17 return false;
18 }
19 } else if map2.contains_key(&c2) {
20 return false;
21 } else {
22 map.insert(c1, c2);
23 }
24 map2.insert(c2, c1);
25 }
26 true
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn test1() {
35 assert_eq!(
36 is_isomorphic(String::from("egg"), String::from("add")),
37 true
38 );
39 assert_eq!(is_isomorphic(String::from("ab"), String::from("aa")), false);
40 }
41}