Sentence Similarity
To determine if two sentences are similar, they must have the same length and each word in the same position in both sentences must be either identical or similar. Similarity between words is defined by the similarPairs
list.
In the Python solution below, we’ll first check if the sentences have the same length. If not, we can return False immediately. Then we’ll convert similarPairs
into a set for quick lookup. Then we’ll iterate over each word in the sentences. If a word from sentence1
and sentence2
is not the same and also not in the similarPairs set, we return False. If we finish the iteration without returning False, it means all words are similar, so we return True.
|
|
This solution has a time complexity of O(n), where n is the maximum length of the sentences, because we iterate over each word in the sentences. The space complexity is O(m), where m is the number of similarPairs, because we convert similarPairs into a set.