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, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].

Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.

Similarity is also 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].

这道题是之前那道 Sentence Similarity 的拓展,那道题说单词之间不可传递,于是乎这道题就变成可以传递了,难度就增加了。不过没有关系,还是用经典老三样来解,BFS,DFS,和 Union Find。先来看 BFS 的解法,其实这道题的本质是无向连通图的问题,首先要做的就是建立这个连通图的数据结构,对于每个结点来说,要记录所有和其相连的结点,建立每个结点和其所有相连结点集合之间的映射,比如对于这三个相似对 (a, b), (b, c),和(c, d),我们有如下的映射关系:

a -> {b}

b -> {a, c}

c -> {b, d}

d -> {c}

那么如果要验证a和d是否相似,就需要用到传递关系,a只能找到b,b可以找到a,c,为了不陷入死循环,将访问过的结点加入一个集合 visited,那么此时b只能去,c只能去d,那么说明a和d是相似的了。用for循环来比较对应位置上的两个单词,如果二者相同,那么直接跳过去比较接下来的。否则就建一个访问即可 visited,建一个队列 queue,然后把 words1 中的单词放入 queue,建一个布尔型变量 succ,标记是否找到,然后就是传统的 BFS 遍历的写法了,从队列中取元素,如果和其相连的结点中有 words2 中的对应单词,标记 succ 为 true,并 break 掉。否则就将取出的结点加入队列 queue,并且遍历其所有相连结点,将其中未访问过的结点加入队列 queue 继续循环,参见代码如下:

解法一:

class Solution {
public:
bool areSentencesSimilarTwo(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);
m[pair.second].insert(pair.first);
}
for (int i = ; i < words1.size(); ++i) {
if (words1[i] == words2[i]) continue;
unordered_set<string> visited;
queue<string> q{{words1[i]}};
bool succ = false;
while (!q.empty()) {
auto t = q.front(); q.pop();
if (m[t].count(words2[i])) {
succ = true; break;
}
visited.insert(t);
for (auto a : m[t]) {
if (!visited.count(a)) q.push(a);
}
}
if (!succ) return false;
}
return true;
}
};

下面来看递归的写法,解题思路跟上面的完全一样,把主要操作都放到了一个递归函数中来写,参见代码如下:

解法二:

class Solution {
public:
bool areSentencesSimilarTwo(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);
m[pair.second].insert(pair.first);
}
for (int i = ; i < words1.size(); ++i) {
unordered_set<string> visited;
if (!helper(m, words1[i], words2[i], visited)) return false;
}
return true;
}
bool helper(unordered_map<string, unordered_set<string>>& m, string& cur, string& target, unordered_set<string>& visited) {
if (cur == target) return true;
visited.insert(cur);
for (string word : m[cur]) {
if (!visited.count(word) && helper(m, word, target, visited)) return true;
}
return false;
}
};

下面这种解法就是碉堡了的联合查找 Union Find 了,这种解法的核心是一个 getRoot 函数,如果两个元素属于同一个群组的话,调用 getRoot 函数会返回相同的值。主要分为两部,第一步是建立群组关系,suppose 开始时每一个元素都是独立的个体,各自属于不同的群组。然后对于每一个给定的关系对,对两个单词分别调用 getRoot 函数,找到二者的祖先结点,如果从未建立过联系的话,那么二者的祖先结点时不同的,此时就要建立二者的关系。等所有的关系都建立好了以后,第二步就是验证两个任意的元素是否属于同一个群组,就只需要比较二者的祖先结点都否相同啦。是不是有点深度学习的赶脚,先建立模型 training,然后再 test。哈哈,博主乱扯的,二者并没有什么联系。这里保存群组关系的数据结构,有时用数组,有时用 HashMap,看输入的数据类型吧,如果输入元素的整型数的话,用 root 数组就可以了,如果是像本题这种的字符串的话,需要用 HashMap 来建立映射,建立每一个结点和其祖先结点的映射。注意这里的祖先结点不一定是最终祖先结点,而最终祖先结点的映射一定是最重祖先结点,所以 getRoot 函数的设计思路就是要找到最终祖先结点,那么就是当结点和其映射结点相同时返回,否则继续循环,可以递归写,也可以迭代写,这无所谓。注意这里第一行判空是相当于初始化,这个操作可以在外面写,就是要让初始时每个元素属于不同的群组,参见代码如下:

解法三:

class Solution {
public:
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if (words1.size() != words2.size()) return false;
unordered_map<string, string> m;
for (auto pair : pairs) {
string x = getRoot(pair.first, m), y = getRoot(pair.second, m);
if (x != y) m[x] = y;
}
for (int i = ; i < words1.size(); ++i) {
if (getRoot(words1[i], m) != getRoot(words2[i], m)) return false;
}
return true;
}
string getRoot(string word, unordered_map<string, string>& m) {
if (!m.count(word)) m[word] = word;
return word == m[word] ? word : getRoot(m[word], m);
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/737

类似题目:

Friend Circles

Accounts Merge

Sentence Similarity

参考资料:

https://leetcode.com/problems/sentence-similarity-ii/

https://leetcode.com/problems/sentence-similarity-ii/discuss/109747/Java-Easy-DFS-solution-with-Explanation

https://leetcode.com/problems/sentence-similarity-ii/discuss/109752/JavaC%2B%2B-Clean-Code-with-Explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 737. Sentence Similarity II 句子相似度之二的更多相关文章

  1. [LeetCode] 737. Sentence Similarity II 句子相似度 II

    Given two sentences words1, words2 (each represented as an array of strings), and a list of similar ...

  2. [LeetCode] Sentence Similarity II 句子相似度之二

    Given two sentences words1, words2 (each represented as an array of strings), and a list of similar ...

  3. LeetCode 737. Sentence Similarity II

    原题链接在这里:https://leetcode.com/problems/sentence-similarity-ii/ 题目: Given two sentences words1, words2 ...

  4. [LeetCode] 734. Sentence Similarity 句子相似度

    Given two sentences words1, words2 (each represented as an array of strings), and a list of similar ...

  5. LeetCode 734. Sentence Similarity

    原题链接在这里:https://leetcode.com/problems/sentence-similarity/ 题目: Given two sentences words1, words2 (e ...

  6. [LeetCode] Number of Islands II 岛屿的数量之二

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

  7. [LeetCode] Shortest Word Distance II 最短单词距离之二

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  8. [LeetCode] 685. Redundant Connection II 冗余的连接之二

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...

  9. [LeetCode] Pascal's Triangle II 杨辉三角之二

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3, ...

随机推荐

  1. 现代WEB前端的性能优化

    现代WEB前端的性能优化 前言:这只是一份学习笔记. 什么是WEB前端 潜在的优化点: DNS是否可以通过缓存减少DNS查询时间? 网络请求的过程走最近的网络环境? 相同的静态资源是否可以缓存? 能否 ...

  2. zabbix 自定义mysql监控

    一.配置zabbix-agent 编辑 /etc/zabbix/zabbix_agentd.conf文件  增加如下两个配置 1.vim /etc/zabbix/zabbix_agentd.conf ...

  3. Javascript 实现倒计时效果

    代码来自于网上. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...

  4. Lucene的全文检索学习

    Lucene的官方网站(Apache的顶级项目):http://lucene.apache.org/ 1.什么是Lucene? Lucene 是 apache 软件基金会的一个子项目,由 Doug C ...

  5. 开源工作流引擎 Workflow Core 的研究和使用教程

    目录 开源工作流引擎 Workflow Core 的研究和使用教程 一,工作流对象和使用前说明 二,IStepBuilder 节点 三,工作流节点的逻辑和操作 容器操作 普通节点 事件 条件体和循环体 ...

  6. JVM底层原理及调优之笔记一

    JVM底层原理及调优 1.java虚拟机内存模型(JVM内存模型) 1.堆(-Xms -Xmx -Xmn) java堆,也称为GC堆,是JVM中所管理的内存中最大的一块内存区域,是线程共享的,在JVM ...

  7. 【转载】Visual Studio2017如何设置打包发布的WinForm应用程序的版本号

    在Visual Studio 2017集成开发工具中,打包发布Winform窗体应用程序的时候,支持设置此次打包发布的Winform窗体应用程序对应的版本号信息,并且支持一次设置后,后续的所有发布版本 ...

  8. vue打包后刷新页面报错:Unexpected token <

    前言 今天遇到了一个很怪的问题,在vue-cli+webpack的项目中,刷新特定页面后页面会变空白,报错为index.html文件中Unexpected token <. 怪点一是开发环境没有 ...

  9. vue学习指南:第十一篇(详细) - Vue的 路由 第一篇 ( router )

    一.路由的配置 路由  vue-router 1. 什么是路由? 路由相当于一个配置对象 路由:就是我们通过不同的url访问不同的内容,通过angular.js 可以实现多视图的单页,现在流行的单页面 ...

  10. jmeter5.1分布式压测

    在使用jmeter压测过程中,可能会度遇到内存溢出的错误,这是为什么呢?因为jmeter是java写的应用,java应用jvm堆内存heap受负载机硬件限制,虽然我们可以调整堆内存大小,但是单机无法支 ...