We can represent a sentence as an array of words, for example, the sentence "I am happy with neetcode" can be represented as arr = ["I","am","happy","with","neetcode"].
Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.
Return true if sentence1 and sentence2 are similar, or false if they are not similar.
Two sentences are similar if:
sentence1[i] and sentence2[i] are similar.Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words a and b are similar, and the words b and c are similar, a and c are not necessarily similar.
Example 1:
Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
Output: trueExplanation: The two sentences have the same length, and each word i of sentence1 is also similar to the corresponding word in sentence2.
Example 2:
Input: sentence1 = ["great"], sentence2 = ["great"], similarPairs = []
Output: trueExplanation: A word is similar to itself.
Example 3:
Input: sentence1 = ["great"], sentence2 = ["doubleplus","good"], similarPairs = [["great","doubleplus"]]
Output: falseExplanation: As they don't have the same length, we return false.
Constraints:
1 <= sentence1.length, sentence2.length <= 10001 <= sentence1[i].length, sentence2[i].length <= 20sentence1[i] and sentence2[i] consist of English letters.0 <= similarPairs.length <= 1000similarPairs[i].length == 21 <= xi.length, yi.length <= 20xi and yi consist of lower-case and upper-case English letters.(xi, yi) are distinct.class Solution(object):
def areSentencesSimilar(self, sentence1, sentence2, similarPairs):
if len(sentence1) != len(sentence2):
return False
wordToSimilarWords = defaultdict(set)
for word1, word2 in similarPairs:
wordToSimilarWords[word1].add(word2)
wordToSimilarWords[word2].add(word1)
for i in range(len(sentence1)):
if sentence1[i] == sentence2[i] or sentence2[i] in wordToSimilarWords[sentence1[i]]:
continue
return False
return TrueWhere is the number of words in
sentence1andsentence2, is the length ofsimilarPairs, and is the average length of words insentence1as well assimilarPairs.