题目#

Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y.

We are given a list A of strings. Every string in A is an anagram of every other string in A. How many groups are there?

anagram 这个词的意思被忽略导致我误理解了题意

Intuition#

我们可以在 Ow 的时间内分辨 两个words 是否相似

一种思想是纯使用暴力算法 : n2W 的时间内判断两个单词是否详细

另一种想法是 枚举一个单词的所有相似紧邻 一个单词之多有 C2w 个紧邻

W2 的时间用来枚举所有的可能相似单词 W 时间

这样我们可以使用 ONW3 的时间 列出所有的单词相邻

py2 版本

class DSU(object,N):
def __init__(self):
self.par=range(N)
def find(self,x):
if(self.par[x]!=x):
self.par[x]= self.find(par[x])
return self.par[x]
def union(self,x,y):
if(x!=y):
self.par[self.find(x)]=self.find(y)
class Solution(object):
def numSimilarGroups(self,A):
N,w=len(A),len(A[0]) # 分别是词的个数和 词的长度
def similar(W1,W2):
diff=0
for x,y in itertools.izip(W1,W2):
if x!=y:
diff=dfif+1
return diff <=2 dsu=DSU(N) if(N<W*W): //如果整个词列表较短, 遍历整个词列表进行计算会更快
for (i1,word1),(i2,word2) in itertools.combinations(enumerate(A),2):#高效的枚举操作 ,也是py支持的非常有用的操作
if similar(word1,word2):
dsu.union(i1,i2) #使用编号作为合并的索引
else:
buckets=collections.defaultdict(set) # values 是set 且具有默认值的字典
for i,word in enumerate(A):
L=list(word) # string 调换中间某几个字符顺序的最佳操作
for j0,j1 in itertools.combinations(xrange(N),2): 组合操作的最佳方式 使用itertools
L[j0], L[j1] = L[j1], L[j0]
buckets["".join(L)].add(i)
L[j0], L[j1] = L[j1], L[j0]
for i1, word in enumerate(A):
for i2 in buckets[word]:
dsu.union(i1, i2)
return sum([for dsu.par[x]==x for x in range(N)]) #并查集变通块数量的查询简易方法

以上的代码虽然正确,但是复杂度高 ,不能通过(py3 的方式重写之后 不能通过py3 的测试)

下面是 加速版本

class Solution:
def numSimilarGroups(self, A):
SA = set(A) # to delete duplicate items
A = list(SA) # make it indexable
L = len(A)
base = [i for i in range(L)] def find(x):
if base[x] != x:
base[x] = find(base[x])
return base[x] def union(x, y):
base[find(x)] = find(y) def check(x, y):
return sum(a!=b for a, b in zip(A[x], A[y])) == 2 if L < len(A[0])**2: # deal with long word with few items
for i1, i2 in itertools.combinations(range(L), 2):
if check(i1, i2):
union(i1, i2)
else: # deal with short word with lots of items
buckets = collections.defaultdict(set)
for i, word in enumerate(A):
for i1, i2 in itertools.combinations(range(len(word)), 2):
if word[i1] != word[i2]: # filter, otherwise it will exceed memory limit
wl = list(word)
wl[i1], wl[i2] = wl[i2], wl[i1]
key = "".join(wl)
if key in SA:
buckets[key].add(i) for i, word in enumerate(A):
for j in buckets[word]:
union(i, j) return sum(base[x] == x for x in range(L))

可以看到 这里将dsu 单独拿出来使用,

然后在枚举 一个单词的所有邻居的时候 也进行了优化 就是如果这个单词的两个位置不一样 我们才认为是一个合法的邻居。

leetcode 839 Similar String Groups的更多相关文章

  1. [LeetCode] 839. Similar String Groups 相似字符串组

    Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it ...

  2. Similar String Groups

    Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it ...

  3. 【LeetCode】839. 相似字符串组 Similar String Groups (Python)

    作者: 负雪明烛 id: fuxuemingzhu 公众号:每日算法题 本文关键词:LeetCode,力扣,算法,算法题,字符串,并查集,刷题群 目录 题目描述 解题思路 并查集 代码 刷题心得 欢迎 ...

  4. [Swift]LeetCode839. 相似字符串组 | Similar String Groups

    Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it ...

  5. 牛客练习赛33 E tokitsukaze and Similar String (字符串哈希hash)

    链接:https://ac.nowcoder.com/acm/contest/308/E 来源:牛客网 tokitsukaze and Similar String 时间限制:C/C++ 2秒,其他语 ...

  6. [LeetCode] Positions of Large Groups 大群组的位置

    In a string S of lowercase letters, these letters form consecutive groups of the same character. For ...

  7. [LeetCode] 800. Similar RGB Color 相似的红绿蓝颜色

    In the following, every capital letter represents some hexadecimal digit from 0 to f. The red-green- ...

  8. 【LeetCode】字符串 string(共112题)

    [3]Longest Substring Without Repeating Characters (2019年1月22日,复习) [5]Longest Palindromic Substring ( ...

  9. 【LeetCode】8. String to Integer (atoi) 字符串转换整数

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:字符串转整数,atoi,题解,Leetcode, 力扣,P ...

随机推荐

  1. lavarel中如何使用memcache

    lavarel中如何使用memcache 一.总结 一句话总结: composer下载包,配置,使用函数 1.memcache是什么? 键值对内存缓存 MemCache是一个自由.源码开放.高性能.分 ...

  2. java.sql.SQLException

    java.sql.SQLException 出错:java.sql.SQLException: com.mchange.v2.c3p0.ComboPooledDataSource[ identityT ...

  3. 在熟练使用2B铅笔前,请不要打开Axure

    在互联网产品领域,Axure已成为产品经理.产品设计师以及交互设计师的必备工具,从某种程度讲,Axure帮助我们建立低保真模型,便于与用户的需求验证,也帮助我们构思交互细节,使前端和开发人员更容易理解 ...

  4. wpf中数据绑定和INotifyPeropertyChanged的理解

    原创:转载请注明出处. 先说数据绑定: XAML代码: <Window x:Class="数据绑定和INotifyPropertyChanged.Window1" Loade ...

  5. jquery刷新局部和全页的方法

    一.全页面刷新方法: window.location.reload()刷新当前页面. parent.location.reload()刷新父亲对象(用于框架) opener.location.relo ...

  6. 详解position定位与定位应用

    定位一直是WEB标准应用中的难点,如果理不清楚定位那么可能应实现的效果实现不了,实现了的效果可能会走样.如果理清了定位的原理,那定位会让网页实现的更加完美.     定位的定义:    在CSS中关于 ...

  7. 从0开始学习ssh之搭建环境

    ssh即struts+spring+Hibernate,从头开始学习这个框架. struts环境配置,首先在apps目录下找到struts2-blank-xxx.war这个文件,这是已经发布好的war ...

  8. windows server 文件夹和搜索选项被禁用了

    当我们需要调整 windows 文件夹相关的配置时,却发现“文件夹和搜索选项”被禁用了,下图是恢复正常的情况.被禁用时显示灰色,不能点击. 下面给出解决步骤: 打开“组策略”. 然后依次展开“用户配置 ...

  9. 嘴巴题8 BZOJ2318: Spoj4060 game with probability Problem

    Time Limit: 1 Sec Memory Limit: 128 MB Submit: 555 Solved: 273 [Submit][Status][Discuss] Description ...

  10. Leetcode949. Largest Time for Given Digits给定数字能组成最大的时间

    给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间. 最小的 24 小时制时间是 00:00,而最大的是 23:59.从 00:00 (午夜)开始算起,过得越久,时间越大. ...