737. Sentence Similarity II

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"].






Solution 1 : dfs 
Solution 2 : union find 



Solution 1 : 


class Solution {
    public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
      // check size 
      if(words1.length != words2.length) return false;
      
      // size is the same 
      // build a map
      HashMap<String, Set<String>> map = new HashMap<>();
      for(String[] pair : pairs){
        String first = pair[0];
        String second = pair[1];
        if(!map.containsKey(first)){
          map.put(first, new HashSet<>());
        }
        map.get(first).add(second);
        if(!map.containsKey(second)){
          map.put(second, new HashSet<>());
        }
        map.get(second).add(first);
      }
      
      // traverse the words 1 and words2 word by word 
      for(int i = 0; i < words1.length; i++){
        String w1 = words1[i];
        String w2 = words2[i];
        
        if(w1.equals(w2)) continue;  // a word is always similar with itself.
        if(!map.containsKey(w1) || !map.containsKey(w2)) return false; // if either of the words exist in the map, return false 
        // else do dfs 
        // use a hashset to record all the strings visited so we can get out of the loop in dfs , avoid stack overflow, dead loop 
        HashSet<String> visited = new HashSet<>();
        if(!dfs(w1, w2, map, visited)) return false;
      }
      return true;
    }
    private boolean dfs(String w1, String w2, HashMap<String, Set<String>> map, HashSet<String> visited){
        
        if(map.get(w1).contains(w2)) return true;
        visited.add(w1);
        for(String nei : map.get(w1)){
            if(!visited.contains(nei) && dfs(nei, w2, map, visited)){
                return true;
            }
        }
        return false;
    }
}






Uf
https://leetcode.com/problems/sentence-similarity-ii/discuss/109749/Simple-Java-Union-Find

This is a good use case for Union-Find, compare to Sentence Similarity I, here the similarity between words are transitive, so all the connected(similar) words should be group into an union represented by their ultimate parent(or family holder, you name it).
The connections can be represented by an parent map Map<String, String> m, which record the direct parent-ship we learned in each pair, but not the ultimate-parent. To build it, go through the input pairs, for each pair<w1, w2>, use the recursive find() method to find the ultimate-parent for both word - parent1, parent2, if they are different, assign parent1 as parent of parent2(or the other way around), so that the to families are merged.
The classic find(x) method will find the ultimate-parent of x. I modified it a little bit, make it do a little of extra initialization work - assign x itself as its parent when it is not initialize - so that we don't have to explicitly initialize the map at the beginning.
Java
class Solution {
    public boolean areSentencesSimilarTwo(String[] a, String[] b, String[][] pairs) {
        if (a.length != b.length) return false;
        Map<String, String> m = new HashMap<>();
        for (String[] p : pairs) {
            String parent1 = find(m, p[0]), parent2 = find(m, p[1]);
            if (!parent1.equals(parent2)) m.put(parent1, parent2);
        }

        for (int i = 0; i < a.length; i++)
            if (!a[i].equals(b[i]) && !find(m, a[i]).equals(find(m, b[i]))) return false;

        return true;
    }

    private String find(Map<String, String> m, String s) {
        if (!m.containsKey(s)) m.put(s, s);
        return s.equals(m.get(s)) ? s : find(m, m.get(s));
    }
}

 

 

 

posted on 2018-09-20 18:26  猪猪&#128055;  阅读(161)  评论(0)    收藏  举报

导航