本文主要是介绍734. 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”].
这一题简单来说就是用hash table把现有的字典存储起来,然后逐一扫描验证就行。
hash table的key都是unique的,那么如何处理同一个word对应多个近义词就是这题的关键。提供两种解法,分别基于unordered_map和unordered_set.
方法一:unordered_map
用一个key对应一个vector< string>,将所有的近义词存起来就是了。
class Solution {
public:bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {int len = words1.size();if (len != words2.size()) return false;unordered_map<string, vector<string>> hash;for (auto p : pairs) {hash[p.first].push_back(p.second);}for (int i = 0; i < len; i++) {if (words1[i] == words2[i]) continue;if (hash.find(words1[i]) != hash.end()) {int flag = false;for (auto s : hash[words1[i]]) {if (words2[i] == s) {flag = true;break;}}if (flag == true) continue;}if (hash.find(words2[i]) != hash.end()) {int flag = false;for (auto s : hash[words2[i]]) {if (words1[i] == s) {flag = true;break;}}if (flag == true) continue;}return false;}return true;}
};
方法二: unordered_set
将一对近义词用特殊符合连成一个字符串存起来。
class Solution {
public:bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {int len = words1.size();if (len != words2.size()) return false;unordered_set<string> hash;for (auto p : pairs) {hash.insert(p.first + "#" + p.second);}for (int i = 0; i < len; i++) {if (words1[i] == words2[i]) continue;if (hash.find(words1[i] + "#" + words2[i]) != hash.end()) continue; if (hash.find(words2[i] + "#" + words1[i]) != hash.end()) continue;return false;}return true;}
};
这里提一下这种container里常见的insert,emplace以及operator[]的区别。
首先[]和insert是一直都有的。[]是find or add,如果本来就有那个key, 直接返回对应的reference,如果没有,创建一个,作default初始化。insert是如果有,不作为,如果没有,copy or move 来创建一个。
emplace是c++11标准中新加的,跟insert很像,如果有,不作为,不会overload。但是一些时候,emplace 会更加高效,简单来说,因为它在创建一个新的element的时候是in place的,没有copy or move 的操作,通过传递参数完成构建,实际上是dynamic memory allocation。
这篇关于734. Sentence Similarity的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!