737.Sentence Similarity II

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

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

Note that the similarity relationistransitive. 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 sentenceswords1 = ["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 likewords1 = ["great"]can never be similar towords2 = ["doubleplus","good"].

Method 1 DFS, O(NP), where NN is the maximum length of words1 and words2, and PP is the length of pairs. Each of NN searches could search the entire graph. O(P) space, the size of pairs.

  • Put each word in pairs in a dict of sets
  • Loop through words1 and words2, do dfs.
class Solution(object):
    def areSentencesSimilarTwo(self, words1, words2, pairs):
        if len(words1) != len(words2):
            return False
        def dfs(w1, w2, hm):
            if w2 in hm[w1]:
                return True
            visited.add(w1)
            for i in hm[w1]:
                if i not in visited and dfs(i, w2, hm):
                    return True
            return False     
        hm = collections.defaultdict(set)
        for i,j in pairs:
            hm[i].add(j)
            hm[j].add(i)
        for i in xrange(len(words1)):
            visited = set()
            w1, w2 = words1[i], words2[i]
            if w1 != w2 and not dfs(w1, w2, hm):
                return False
        return True

results matching ""

    No results matching ""