884. Uncommon Words from Two Sentences

We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words. 

You may return the list in any order.

 

Example 1:

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]

Example 2:

Input: A = "apple apple", B = "banana"
Output: ["banana"]

 

Note:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A and B both contain only spaces and lowercase letters.

Rust Solution

struct Solution;

use std::collections::BTreeMap;

impl Solution {
    fn uncommon_from_sentences(a: String, b: String) -> Vec<String> {
        let mut hs: BTreeMap<&str, i32> = BTreeMap::new();
        a.split_whitespace().for_each(|s| {
            *hs.entry(s).or_default() += 1;
        });
        b.split_whitespace().for_each(|s| {
            *hs.entry(s).or_default() += 1;
        });
        let mut res: Vec<String> = vec![];
        for (s, v) in hs {
            if v == 1 {
                res.push(s.to_string());
            }
        }
        res
    }
}

#[test]
fn test() {
    let a = "this apple is sweet".to_string();
    let b = "this apple is sour".to_string();
    let res: Vec<String> = vec_string!["sour", "sweet"];
    assert_eq!(Solution::uncommon_from_sentences(a, b), res);
    let a = "apple apple".to_string();
    let b = "banana".to_string();
    let res: Vec<String> = vec_string!["banana"];
    assert_eq!(Solution::uncommon_from_sentences(a, b), res);
}

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