-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0734-sentence-similarity.js
More file actions
45 lines (37 loc) · 1.37 KB
/
0734-sentence-similarity.js
File metadata and controls
45 lines (37 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Sentence Similarity
* Time Complexity: O(N + P * L)
* Space Complexity: O(P * L)
*/
var areSentencesSimilar = function (sentence1, sentence2, similarPairs) {
const primarySentenceWordCount = sentence1.length;
const secondarySentenceWordCount = sentence2.length;
if (primarySentenceWordCount !== secondarySentenceWordCount) {
return false;
}
const wordSimilarityLookup = new Set();
const numberOfSimilarPairs = similarPairs.length;
let currentPairIndex = 0;
while (currentPairIndex < numberOfSimilarPairs) {
const pairEntry = similarPairs[currentPairIndex];
const firstMember = pairEntry[0];
const secondMember = pairEntry[1];
wordSimilarityLookup.add(`${firstMember}:${secondMember}`);
wordSimilarityLookup.add(`${secondMember}:${firstMember}`);
currentPairIndex++;
}
let wordComparisonIndex = 0;
const commonSentenceLength = primarySentenceWordCount;
while (wordComparisonIndex < commonSentenceLength) {
const wordFromFirstSentence = sentence1[wordComparisonIndex];
const wordFromSecondSentence = sentence2[wordComparisonIndex];
if (wordFromFirstSentence !== wordFromSecondSentence) {
const similarityQueryKey = `${wordFromFirstSentence}:${wordFromSecondSentence}`;
if (!wordSimilarityLookup.has(similarityQueryKey)) {
return false;
}
}
wordComparisonIndex++;
}
return true;
};