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].

734. Sentence Similarity 的拓展。不同点,这题的相似单词可以传递。

解法1:DFS。本质是无向连通图的问题,把pairs数组中的每一对相似的字符串视为无向图上的两个结点,对每个结点要记录所有和其相连的结点,比如(a, b), (b, c)和(c, d)的映射关系:a -> {b},  b -> {a, c},  c -> {b, d},  d -> {c}。要验证a和d是否相似,从a只能找到b,b可以找到a、c, a访问过,将访问过的结点加入一个集合visited,此时只能访问c,c里面有b、d,找到d,说明a和d相似。

解法2:BFS。与 DFS 类似,只是写成迭代形式。

解法3:Union Find

Java:

class Solution {
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
if (words1.length != words2.length) {
return false;
}
// Build the graph of pairs
HashMap<String, Set<String>> pairMap = new HashMap<>();
for (String[] pair : pairs) {
// Create keys(words in [][]pairs without duplication) and empty set
if (!pairMap.containsKey(pair[0])) {
pairMap.put(pair[0], new HashSet<String>());
}
if (!pairMap.containsKey(pair[1])) {
pairMap.put(pair[1], new HashSet<String>());
}
// Add the corresponding pairs to each other
pairMap.get(pair[0]).add(pair[1]);
pairMap.get(pair[1]).add(pair[0]);
} // Iterate throught each word in both input strings and do DFS search
for (int i = 0; i < words1.length; i++) {
// If same, then we don't need to do DFS search
if (words1[i].equals(words2[i])) continue;
// If they are not the same and no such strings in the pairs
if (!pairMap.containsKey(words1[i]) || !pairMap.containsKey(words2[i])) return false;
// Do DFS search, initialize the set to prevent revisiting.
if (!dfs(words1[i], words2[i], pairMap, new HashSet<>())) return false;
}
return true;
} public boolean dfs(String source, String target, HashMap<String, Set<String>> pairMap, HashSet<String> visited) {
if (pairMap.get(source).contains(target)) {
return true;
}
// Mark as visited
visited.add(source);
for (String next : pairMap.get(source)) {
// DFS other connected node, except the mirrowed string
if (!visited.contains(next) && next.equals(target) ||
!visited.contains(next) && dfs(next, target, pairMap, visited)) {
return true;
}
}
// We've done dfs still can't find the target
return false;
}
}  

Java: Union Find

class Solution {
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
if(words1.length!=words2.length) return false;
Map<String, String> map = new HashMap<>();
for(String[] pair : pairs){
String parent0 = find(pair[0], map);
String parent1 = find(pair[1], map);
if(!parent0.equals(parent1)) map.put(parent0, parent1);
}
int n = words1.length;
for(int i=0; i<n; i++){
if (!words1[i].equals(words2[i]) && !find(words1[i], map).equals(find(words2[i], map))) return false;
}
return true;
} private String find(String word, Map<String, String> map){
if(!map.containsKey(word)) return word;
String str = word;
while(map.containsKey(str)){
str = map.get(str);
}
map.put(word, str);
return str;
}
}

Python: DFS

class Solution(object):
def areSentencesSimilarTwo(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2): return False
similars = collections.defaultdict(set)
for w1, w2 in pairs:
similars[w1].add(w2)
similars[w2].add(w1) def dfs(words1, words2, visits):
for similar in similars[words2]:
if words1 == similar:
return True
elif similar not in visits:
visits.add(similar)
if dfs(words1, similar, visits):
return True
return False for w1, w2 in zip(words1, words2):
if w1 != w2 and not dfs(w1, w2, set([w2])):
return False
return True  

Python:BFS

class Solution(object):
def areSentencesSimilarTwo(self, words1, words2, pairs):
if len(words1) != len(words2): return False
graph = collections.defaultdict(list)
for w1, w2 in pairs:
graph[w1].append(w2)
graph[w2].append(w1) for w1, w2 in zip(words1, words2):
stack, seen = [w1], {w1}
while stack:
word = stack.pop()
if word == w2: break
for nei in graph[word]:
if nei not in seen:
seen.add(nei)
stack.append(nei)
else:
return False
return True

Python: DSU(Disjoint Set Union)  

class DSU:
def __init__(self, N):
self.par = range(N)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
self.par[self.find(x)] = self.find(y) class Solution(object):
def areSentencesSimilarTwo(self, words1, words2, pairs):
if len(words1) != len(words2): return False index = {}
count = itertools.count()
dsu = DSU(2 * len(pairs))
for pair in pairs:
for p in pair:
if p not in index:
index[p] = next(count)
dsu.union(index[pair[0]], index[pair[1]]) return all(w1 == w2 or
w1 in index and w2 in index and
dsu.find(index[w1]) == dsu.find(index[w2])
for w1, w2 in zip(words1, words2))  

C++: DFS

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 = 0; 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;
}
};

C++: BFS

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 = 0; 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;
}
};

C++:  

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 = 0; 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);
}
};

  

类似题目:

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

[LeetCode] 547. Friend Circles 朋友圈

721. Accounts Merge  

All LeetCode Questions List 题目汇总

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

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

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

  2. LeetCode 737. Sentence Similarity II

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

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

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

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

    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. 734. Sentence Similarity 有字典数组的相似句子

    [抄题]: Given two sentences words1, words2 (each represented as an array of strings), and a list of si ...

  7. NLP入门(一)词袋模型及句子相似度

      本文作为笔者NLP入门系列文章第一篇,以后我们就要步入NLP时代.   本文将会介绍NLP中常见的词袋模型(Bag of Words)以及如何利用词袋模型来计算句子间的相似度(余弦相似度,cosi ...

  8. 论文阅读笔记: Multi-Perspective Sentence Similarity Modeling with Convolution Neural Networks

    论文概况 Multi-Perspective Sentence Similarity Modeling with Convolution Neural Networks是处理比较两个句子相似度的问题, ...

  9. Leetcode 137. 只出现一次的数字 II - 题解

    Leetcode 137. 只出现一次的数字 II - 题解 137. Single Number II 在线提交: https://leetcode.com/problems/single-numb ...

随机推荐

  1. cron使用

    每天1点执行脚本 0 1 * * * /home/xtrabackup.sh service crond restart / systemctl restart crond 每隔5分钟 */5 * * ...

  2. 云打印 对Echo的Beta产品测试报告

    云打印 对Echo的Beta产品测试报告 课程名称:软件工程1916|W(福州大学) 团队名称: 云打印 作业要求: 项目Beta冲刺(团队) 作业目标:作业集合 团队队员 队员学号 队员姓名 个人博 ...

  3. Spring Boot 2实现分布式锁——这才是实现分布式锁的正确姿势!

    参考资料 网址 Spring Boot 2实现分布式锁--这才是实现分布式锁的正确姿势! http://www.spring4all.com/article/6892

  4. MANIFEST.MF文件对Import-Package/Export-Package重排列

    众所周知,MANIFEST.MF文件中的空格开头的行是相当于拼接在上一行末尾的.很多又长又乱的Import-Package或者Export-Package,有时候想要搜索某个package却可能被换行 ...

  5. 阿里云部署,ubuntu, 连接服务器 |更新源| 安装node |安装mysql

    1.连接服务器 xshell 新建连接 ssh root@1.1.1.1 2.更新源 apt-get update 3.安装node apt-get install -y curl curl -sL ...

  6. css绘制各种图形,三角形,长方形,梯形

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA8cAAADVCAIAAAD1mxUAAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWX ...

  7. spi调试步骤,mcp2515调试整理

    1.先查看也硬件电路,一般都是单片机作为master,其他芯片作为slave.单片机的MOSI对应从机的SI,单片机的MISO对应从机的SO,如果两个引脚接反了,那是怎么调试都没有效果的. 2.单片机 ...

  8. 平衡二叉树(Java)

    package com.rao.linkList; /** * @author Srao * @className AvlTree * @date 2019/12/3 21:23 * @package ...

  9. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException 拒绝访问 / 出现了内部错误 c# – 当使用X509Certificate2加载p12/pfx文件时出现

    环境:iis/netcore 2.2 初始调用:X509Certificate2 certificate = new X509Certificate2(input.Path, CER_PASSWORD ...

  10. /proc文件系统的特点和/proc文件的说明

    /proc文件系统是一种特殊的.由软件创建的文件系统,内核使用它向外界导出信息,/proc系统只存在内存当中,而不占用外存空间. /proc下面的每个文件都绑定于一个内核函数,用户读取文件时,该函数动 ...