summaryrefslogtreecommitdiff
path: root/buddy-strings/src/main.rs
blob: dbc982c056d6f9ebc115102a03c2530d1fab1e1a (plain)
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
fn main() {
    println!("Hello, world!");
    let tests = [
        ("ab", "ba", true),
        ("ab", "ab", false),
        ("aa", "aa", true),
        ("abcaa", "abcbb", false)
    ];

    for test in tests {
        println!("{:?} {:?} is {} should be {}", test.0, test.1,
                 Solution::buddy_strings(test.0.clone().to_string(), test.1.clone().to_string()),
        test.2);
    }
}
struct Solution;

use std::collections::HashMap;

impl Solution {
    pub fn buddy_strings(s: String, goal: String) -> bool {
        let mut occurences_s = HashMap::new();
        let mut occurences_goal = HashMap::new();
        let similarities = s.chars().zip(goal.chars()).filter(|(a,b)| {
            *occurences_s.entry(a.clone()).or_insert(1) += 1; 
            *occurences_goal.entry(b.clone()).or_insert(1) += 1; 
            a != b})
            .count();
        s.len() == goal.len() && occurences_s == occurences_goal && (similarities == 2 || (similarities == 0 && occurences_s.values().any(|&x| x > 2)))
    }
}