|
|
发表于 2017-9-19 21:11:01
|
显示全部楼层
本帖最后由 gunjang 于 2017-9-19 22:14 编辑
O(n2)可以的,用set或dict,如果字母对已存在,则更新,否则新建一个字母对
最后有几个set或dict就是几组
哦哦,没有考虑 ab cd,最后ac的情况,最后再来一轮合并就可以了
- setlist=[]
- def update(a,b):
- global setlist
- for aset in setlist:
- if a in aset:
- aset.add(b)
- return
- elif b in aset:
- aset.add(a)
- return
- aset = set([a,b])
- setlist.append(aset)
- def merge():
- global setlist
- for i in range(len(setlist)-1, 0, -1):
- for j in range(i):
- if setlist[i] & setlist[j] != set([]):
- setlist[j] |= setlist[i]
- #remove i
- setlist.remove(setlist[i])
- break
- update('a', 'b')
- update('c', 'd')
- update('a', 'd')
- update('x', 'y')
- update('x', 'z')
- merge()
- print(setlist) #[{'b', 'c', 'a', 'd'}, {'z', 'y', 'x'}]
复制代码
随便写的 |
|