[LeetCode] Sentence Similarity

734. Sentence Similarity

We can represent a sentence as an array of words, for example, the sentence “I am happy with leetcode” can be represented as arr = [“I”,”am”,happy”,”with”,”leetcode”].

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:

  • They have the same length (i.e., the same number of words)
  • 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool areSentencesSimilar(vector<string>& s1, vector<string>& s2, vector<vector<string>>& similarPairs) {
if(s1.size() != s2.size()) return false;
map<string, unordered_set<string>> p;
for(auto vec : similarPairs) {
p[vec[0]].insert(vec[1]);
p[vec[1]].insert(vec[0]);
}
for(int i = 0; i < s1.size(); i++) {
if(s1[i] == s2[i] or p[s1[i]].count(s2[i])) continue;
return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/17/PS/LeetCode/sentence-similarity/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.