[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"] can never be similar to words2 = ["doubleplus","good"].

Note:

  • The length of words1 and words2 will not exceed 1000.
  • The length of pairs will not exceed 2000.
  • The length of each pairs[i] will be 2.
  • The length of each words[i] and pairs[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;
    }
};

 

類似題目:

Friend Circles

Accounts Merge

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM