-
Notifications
You must be signed in to change notification settings - Fork 0
/
isomorphic-strings.rs
65 lines (59 loc) · 1.57 KB
/
isomorphic-strings.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
struct Solution;
impl Solution {
pub fn is_isomorphic(s: String, t: String) -> bool {
use std::collections::HashMap;
let mut s_m: HashMap<char, char> = HashMap::new();
let mut t_m: HashMap<char, char> = HashMap::new();
let t = t.chars().collect::<Vec<char>>();
for (i, c) in s.chars().enumerate() {
let t_c = t[i];
if let Some(&v) = s_m.get(&c) {
if v != t_c {
return false;
}
} else if let Some(&v) = t_m.get(&t_c) {
if v != c {
return false;
}
} else {
s_m.insert(c, t_c);
t_m.insert(t_c, c);
}
}
true
}
}
fn main() {
let tests = vec![
("bbbaaaba", "aaabbbba"),
("egg", "add"),
("paper", "title"),
("a", "a"),
("aaeaa", "uuxyy"),
("badc", "baba"),
];
for (s, t) in tests {
println!(
"{s}, {t}: {}",
Solution::is_isomorphic(s.to_string(), t.to_string())
);
}
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test() {
let tests = vec![
("bbbaaaba", "aaabbbba", false),
("egg", "add", true),
("paper", "title", true),
("a", "a", true),
("aaeaa", "uuxyy", false),
("badc", "baba", false),
];
for (s, t, r) in tests {
assert_eq!(Solution::is_isomorphic(s.to_string(), t.to_string()), r);
}
}
}