737. Sentence Similarity II

Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.

For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].

Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.

Similarity is also symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.

Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs.

Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].

Note:

  • The length of words1 and words2 will not exceed 1000.
  • The length of pairs will not exceed 2000.
  • The length of each pairs[i] will be 2.
  • The length of each words[i] and pairs[i][j] will be in the range [1, 20].

 

Rust Solution

struct Solution;

use std::collections::HashMap;

struct UnionFind {
    parent: Vec<usize>,
    n: usize,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        let parent = (0..n).collect();
        UnionFind { parent, n }
    }

    fn find(&mut self, i: usize) -> usize {
        let j = self.parent[i];
        if i == j {
            j
        } else {
            let k = self.find(j);
            self.parent[i] = k;
            k
        }
    }

    fn union(&mut self, i: usize, j: usize) {
        let i = self.find(i);
        let j = self.find(j);
        if i != j {
            self.parent[i] = j;
            self.n -= 1;
        }
    }
}

impl Solution {
    fn are_sentences_similar_two(
        words1: Vec<String>,
        words2: Vec<String>,
        pairs: Vec<Vec<String>>,
    ) -> bool {
        if words1.len() != words2.len() {
            return false;
        }
        let mut id: HashMap<String, usize> = HashMap::new();
        for w in &words1 {
            id.insert(w.to_string(), 0);
        }
        for w in &words2 {
            id.insert(w.to_string(), 0);
        }
        for pair in &pairs {
            id.insert(pair[0].to_string(), 0);
            id.insert(pair[1].to_string(), 0);
        }
        for (i, (_, v)) in id.iter_mut().enumerate() {
            *v = i;
        }
        let n = id.len();
        let mut uf = UnionFind::new(n);
        for pair in &pairs {
            uf.union(id[&pair[0]], id[&pair[1]]);
        }
        for (w1, w2) in words1.into_iter().zip(words2.into_iter()) {
            if uf.find(id[&w1]) != uf.find(id[&w2]) {
                return false;
            }
        }

        true
    }
}

#[test]
fn test() {
    let words1 = vec_string!["great", "acting", "skills"];
    let words2 = vec_string!["fine", "drama", "talent"];
    let pairs = vec_vec_string![
        ["great", "good"],
        ["fine", "good"],
        ["acting", "drama"],
        ["skills", "talent"]
    ];
    let res = true;
    assert_eq!(
        Solution::are_sentences_similar_two(words1, words2, pairs),
        res
    );
}

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