LeetCode 737. Sentence Similarity II

原题链接在这里:https://leetcode.com/problems/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].

题解:

In order to fulfill transitive, we could use Union-Find.

For each pair, find both ancestor, and have one as parent of the other.

Then when comparing the words1 and words2, if both word are neight equal nor having the same ancestor, then it is not similar, return false.

Time Complexity: O((m+n)*logm). m = pairs.size(). n = words1.length. find takes O(logm). With path comparison and union by rank, it takes amatorize O(1).

Space: O(m).

AC Java: 

 1 class Solution {
 2     public boolean areSentencesSimilarTwo(String[] words1, String[] words2, List<List<String>> pairs) {
 3         if(words1.length != words2.length){
 4             return false;
 5         }
 6         
 7         HashMap<String, String> hm = new HashMap<>();
 8         for(List<String> pair : pairs){
 9             String p1 = find(hm, pair.get(0));
10             String p2 = find(hm, pair.get(1));
11             hm.put(p1, p2);
12         }
13         
14         for(int i = 0; i<words1.length; i++){
15             if(!words1[i].equals(words2[i]) && !find(hm, words1[i]).equals(find(hm, words2[i]))){
16                 return false;
17             }
18         }
19         
20         return true;
21     }
22     
23     private String find(HashMap<String, String> hm, String s){
24         hm.putIfAbsent(s, s);
25         return s.equals(hm.get(s)) ? s : find(hm, hm.get(s));
26     }
27 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11949268.html