Advertisement
nikunjsoni

737

May 2nd, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<vector<string>>& pairs) {
  4.         if(words1.size() != words2.size()) return false;
  5.         unordered_map<string, string> m;
  6.         for(auto p: pairs){
  7.             string p1 = find(m, p[0]);
  8.             string p2 = find(m, p[1]);
  9.             if(p1 != p2)
  10.                 m[p1] = p2;
  11.         }
  12.        
  13.         for(int i=0; i<words1.size(); i++)
  14.             if(find(m, words1[i]) != find(m, words2[i]))
  15.                 return false;
  16.        
  17.         return true;
  18.     }
  19.    
  20.     string find(unordered_map<string, string> &m, string word){
  21.         if(!m.count(word))
  22.             m[word] = word;
  23.         return (m[word] == word) ? word : (m[word] = find(m, m[word]));
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement