859. Buddy Strings

Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

 

Example 1:

Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.

Example 2:

Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.

Example 3:

Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false

 

Constraints:

  • 0 <= A.length <= 20000
  • 0 <= B.length <= 20000
  • A and B consist of lowercase letters.

Rust Solution

struct Solution;

use std::collections::HashSet;

impl Solution {
    fn buddy_strings(a: String, b: String) -> bool {
        let a: Vec<char> = a.chars().collect();
        let b: Vec<char> = b.chars().collect();
        let n = a.len();
        let m = b.len();
        if n != m {
            return false;
        }
        if a == b {
            let mut hs: HashSet<char> = HashSet::new();
            let mut sum = 0;
            for &c in &a {
                if !hs.insert(c) {
                    sum += 1;
                }
            }
            sum != 0
        } else {
            let mut pair: Vec<usize> = vec![];
            for i in 0..n {
                if a[i] != b[i] {
                    pair.push(i);
                }
            }
            if pair.len() == 2 {
                let i = pair[0];
                let j = pair[1];
                a[i] == b[j] && a[j] == b[i]
            } else {
                false
            }
        }
    }
}

#[test]
fn test() {
    let a = "ab".to_string();
    let b = "ba".to_string();
    assert_eq!(Solution::buddy_strings(a, b), true);
    let a = "ab".to_string();
    let b = "ab".to_string();
    assert_eq!(Solution::buddy_strings(a, b), false);
    let a = "aa".to_string();
    let b = "aa".to_string();
    assert_eq!(Solution::buddy_strings(a, b), true);
    let a = "aaaaaaabc".to_string();
    let b = "aaaaaaacb".to_string();
    assert_eq!(Solution::buddy_strings(a, b), true);
    let a = "".to_string();
    let b = "aa".to_string();
    assert_eq!(Solution::buddy_strings(a, b), false);
}

Having problems with this solution? Click here to submit an issue on github.