前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 737. 句子相似性 II(并查集)

LeetCode 737. 句子相似性 II(并查集)

作者头像
Michael阿明
发布2021-02-19 10:55:56
9790
发布2021-02-19 10:55:56
举报
文章被收录于专栏:Michael阿明学习之路

文章目录

1. 题目

给定两个句子 words1, words2 (每个用字符串数组表示),和一个相似单词对的列表 pairs ,判断是否两个句子是相似的。

例如,当相似单词对是 pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]的时候,words1 = ["great", "acting", "skills"]words2 = ["fine", "drama", "talent"] 是相似的。

注意相似关系是 具有 传递性的。 例如,如果 “great” 和 “fine” 是相似的,“fine” 和 “good” 是相似的,则 “great” 和 “good” 是相似的。

而且,相似关系是具有对称性的。 例如,“great” 和 “fine” 是相似的相当于 “fine” 和 “great” 是相似的。

并且,一个单词总是与其自身相似。 例如,句子 words1 = [“great”], words2 = [“great”], pairs = [] 是相似的,尽管没有输入特定的相似单词对。

最后,句子只会在具有相同单词个数的前提下才会相似。 所以一个句子 words1 = [“great”] 永远不可能和句子 words2 = [“doubleplus”,“good”] 相似。

代码语言:javascript
复制
注:
words1 and words2 的长度不会超过 1000。
pairs 的长度不会超过 2000。
每个pairs[i] 的长度为 2。
每个 words[i] 和 pairs[i][j] 的长度范围为 [1, 20]。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sentence-similarity-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

数据结构–并查集(Disjoint-Set)

代码语言:javascript
复制
class dsu
{
	unordered_map<string,string> f;
public:
	dsu(unordered_set<string> &s)
	{
		for(auto& w : s)
    		f[w] = w;//并查集初始化
	}
	void merge(string& a, string& b)
	{
		string fa = find(a);
		string fb = find(b);
		f[fa] = fb;
	}
	string find(string a)
	{
		string origin = a;
		while(a != f[a])
			a = f[a];
		return f[origin] = a;
	}
};
class Solution {
public:
    bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<vector<string>>& pairs) {
    	if(words1.size() != words2.size())
    		return false;
    	unordered_set<string> s;
    	for(auto& p : pairs)
    	{
    		s.insert(p[0]);
    		s.insert(p[1]);
    	}
    	dsu u(s);//并查集
    	for(auto& p : pairs)
    		u.merge(p[0], p[1]);//merge
    	for(int i = 0; i < words1.size(); ++i)
    	{
    		if(words1[i] == words2[i])
    			continue;
    		//并查集find
    		if(u.find(words1[i]) != u.find(words2[i]))
    			return false;
    	}
    	return true;
    }
};

480 ms 57 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/08/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档