Sentence Similarity II
Description
null
Solution(javascript)
/**
* @param {string[]} words1
* @param {string[]} words2
* @param {string[][]} pairs
* @return {boolean}
*/
const areSentencesSimilarTwo = function (words1, words2, pairs) {
if (words1.length !== words2.length) {
return false
}
const parent = {}
const root = (a) => {
parent[a] = parent[a] || a
while (a !== parent[a]) {
a = parent[a]
}
return a
}
const union = (a, b) => {
const rootA = root(a)
const rootB = root(b)
if (rootA === rootB) {
return
}
parent[rootA] = rootB
}
const connected = (a, b) => root(a) === root(b)
pairs.forEach(([a, b]) => {
union(a, b)
})
return words1.every((word1, index) => connected(word1, words2[index]))
}