[LeetCode] Sentence Similarity 句子相似度
Given two sentences words1, words2
(each represented as an array of strings), and a list of similar word pairs pairs
, determine if two sentences are similar.
For example, "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]
Note that the similarity relation is not transitive. For example, if "great" and "fine" are similar, and "fine" and "good" are similar, "great" and "good" are not necessarily similar.
However, similarity is symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = []
are similar, even though there are no specified similar word pairs.
Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"]
words2 = ["doubleplus","good"]
.
Note:
- The length of
words1
andwords2
will not exceed1000
. - The length of
pairs
will not exceed2000
. - The length of each
pairs[i]
will be2
. - The length of each
words[i]
andpairs[i][j]
will be in the range[1, 20]
.
這道題給了我們兩個句子,問這兩個句子是否是相似的。判定的條件是兩個句子的單詞數要相同,而且每兩個對應的單詞要是相似度,這裡會給一些相似的單詞對,這裡說明了單詞對的相似具有互逆性但是沒有傳遞性。看到這裡博主似乎已經看到了Follow up了,加上傳遞性就是一個很好的拓展。那麼這裡沒有傳遞性,就使得問題變得很容易了,我們只要建立一個單詞和其所有相似單詞的集合的對映就可以了,比如說如果great和fine類似,且great和good類似,那麼就有下面這個對映:
great -> {fine, good}
所以我們在逐個檢驗兩個句子中對應的單詞時就可以直接去對映中找,注意有可能遇到的單詞對時反過來的,比如fine和great,所以我們兩個單詞都要帶到對映中去查詢,只要有一個能查詢到,就說明是相似的,反之,如果兩個都沒查詢到,說明不相似,直接返回false,參見程式碼如下:
class Solution { public: bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) { if (words1.size() != words2.size()) return false; unordered_map<string, unordered_set<string>> m; for (auto pair : pairs) { m[pair.first].insert(pair.second); } for (int i = 0; i < words1.size(); ++i) { if (words1[i] == words2[i]) continue; if (!m[words1[i]].count(words2[i]) && !m[words2[i]].count(words1[i])) return false; } return true; } };
類似題目: