Advertisement
1988coder

734. Sentence Similarity

Dec 30th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. /**
  2.  * Time Complexity: O(N + P) Space Complexity : O(P)
  3.  *
  4.  * N = length of words1. P = size of pairs.
  5.  */
  6. class Solution {
  7.     public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
  8.         if (words1 == null || words2 == null || words1.length != words2.length) {
  9.             return false;
  10.         }
  11.  
  12.         Map<String, Set<String>> pairsMap = new HashMap();
  13.         for (String[] pair : pairs) {
  14.             if (!pairsMap.containsKey(pair[0])) {
  15.                 pairsMap.put(pair[0], new HashSet<String>());
  16.             }
  17.             if (!pairsMap.containsKey(pair[1])) {
  18.                 pairsMap.put(pair[1], new HashSet<String>());
  19.             }
  20.             pairsMap.get(pair[0]).add(pair[1]);
  21.             pairsMap.get(pair[1]).add(pair[0]);
  22.         }
  23.  
  24.         for (int i = 0; i < words1.length; i++) {
  25.             if (words1[i].equals(words2[i])) {
  26.                 continue;
  27.             }
  28.             if (!pairsMap.containsKey(words1[i])) {
  29.                 return false;
  30.             }
  31.             if (!pairsMap.get(words1[i]).contains(words2[i])) {
  32.                 return false;
  33.             }
  34.         }
  35.  
  36.         return true;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement