lifeiteng

734. Sentence Similarity

Sep 12th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. class Solution {
  2.     public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
  3.         int m = words1.length, n = words2.length;
  4.         if(m != n) return false;
  5.         Map<String, Set<String>> map = new HashMap<>();
  6.         for(String[] pair : pairs)
  7.         {
  8.             String u = pair[0], v = pair[1];
  9.             if(!map.containsKey(u)) map.put(u, new HashSet<>());
  10.             if(!map.containsKey(v)) map.put(v, new HashSet<>());
  11.             map.get(u).add(v);
  12.             map.get(v).add(u);
  13.         }
  14.         for(int i = 0; i < m; i++)
  15.         {
  16.             String w1 = words1[i], w2 = words2[i];
  17.             if(w1.equals(w2) || map.containsKey(w1) && map.get(w1).contains(w2) ||
  18.                map.containsKey(w2) && map.get(w2).contains(w1)) continue;
  19.             return false;
  20.         }
  21.         return true;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment