当前位置:网站首页>Simulation volume leetcode [general] 1061 Arrange the smallest equivalent strings in dictionary order
Simulation volume leetcode [general] 1061 Arrange the smallest equivalent strings in dictionary order
2022-07-06 06:17:00 【Encounter simulation volume】
Summary : Simulation volume Leetcode Summary of questions
1061. The smallest equivalent string in lexicographic order
Give two strings of the same length s1 and s2 , There is also a string baseStr .
among s1[i] and s2[i] It's a set of equivalent characters .
for instance , If s1 = “abc” And s2 = “cde”, Then there is ‘a’ == ‘c’, ‘b’ == ‘d’, ‘c’ == ‘e’.
Equivalent characters follow the general rules of any equivalence relationship :
reflexivity :‘a’ == ‘a’
symmetry :‘a’ == ‘b’ There must be ‘b’ == ‘a’
Transitivity :‘a’ == ‘b’ And ‘b’ == ‘c’ That means ‘a’ == ‘c’
for example , s1 = “abc” and s2 = “cde” The equivalent information is the same as in the previous example , that baseStr = “eed” , “acd” or “aab”, All three strings are equivalent , and “aab” yes baseStr The smallest equivalent string in dictionary order
utilize s1 and s2 The equivalent information of , Find out and return to baseStr The smallest equivalent string in lexicographic order .
Example 1:
Input :s1 = “parker”, s2 = “morris”, baseStr = “parser”
Output :“makkek”
explain : according to A and B Equivalent information in , We can divide these characters into [m,p], [a,o], [k,r,s], [e,i] common 4 Group . The characters in each group are equivalent , And in dictionary order . So the answer is “makkek”.
Example 2:
Input :s1 = “hello”, s2 = “world”, baseStr = “hold”
Output :“hdld”
explain : according to A and B Equivalent information in , We can divide these characters into [h,w], [d,e,o], [l,r] common 3 Group . So only S The second character in ‘o’ become ‘d’, The final answer is “hdld”.
Example 3:
Input :s1 = “leetcode”, s2 = “programs”, baseStr = “sourcecode”
Output :“aauaaaaada”
explain : We can A and B The equivalent characters in are divided into [a,o,e,r,s,c], [l,p], [g,t] and [d,m] common 4 Group , therefore S In addition to ‘u’ and ‘d’ All the other letters are converted into ‘a’, The final answer is “aauaaaaada”.
Tips :
1 <= s1.length, s2.length, baseStr <= 1000
s1.length == s2.length
character string s1, s2, and baseStr Only from ‘a’ To ‘z’ The lowercase letters of .
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/lexicographically-smallest-equivalent-string
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Code :
import string
from leetcode_python.utils import *
class UnionFindSet(object):
""" Union checking set """
def __init__(self, data_list):
""" Initialize two dictionaries , A parent node that saves nodes , Another one saves the size of the parent node When initializing , Set the parent node of the node as itself ,size Set to 1"""
self.parent_dict = {
}
self.size_dict = {
}
for node in data_list:
self.parent_dict[node] = node
self.size_dict[node] = 1
def find(self, node):
""" Use recursion to find the parent node When finding the parent node , By the way, move the current node to the parent node This operation is an optimization """
father = self.parent_dict[node]
if(node != father):
if father != self.parent_dict[father]: # When reducing tree height optimization , Ensure that the parent node size dictionary is correct
self.size_dict[father] -= 1
father = self.find(father)
self.parent_dict[node] = father
return father
def isConnected(self, node_a, node_b):
""" Check whether the two nodes are in the same set """
return self.find(node_a) == self.find(node_b)
def union(self, node_a, node_b):
""" Merge the two sets together """
if node_a is None or node_b is None:
return
a_head = self.find(node_a)
b_head = self.find(node_b)
if(a_head != b_head):
a_set_size = self.size_dict[a_head]
b_set_size = self.size_dict[b_head]
if(a_head < b_head):
self.parent_dict[b_head] = a_head
self.size_dict[a_head] = a_set_size + b_set_size
else:
self.parent_dict[a_head] = b_head
self.size_dict[b_head] = a_set_size + b_set_size
class Solution:
def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
unionset = UnionFindSet(string.ascii_lowercase)
for c1,c2 in zip(s1,s2): unionset.union(c1,c2)
return ''.join(unionset.find(c)for c in baseStr)
def test(data_test):
s = Solution()
data = data_test # normal
# data = [list2node(data_test[0])] # list turn node
return s.smallestEquivalentString(*data)
def test_obj(data_test):
result = [None]
obj = Solution(*data_test[1][0])
for fun, data in zip(data_test[0][1::], data_test[1][1::]):
if data:
res = obj.__getattribute__(fun)(*data)
else:
res = obj.__getattribute__(fun)()
result.append(res)
return result
if __name__ == '__main__':
datas = [
["parker","morris","parser"],
]
for data_test in datas:
t0 = time.time()
print('-' * 50)
print('input:', data_test)
print('output:', test(data_test))
print(f'use time:{
time.time() - t0}s')
remarks :
GitHub:https://github.com/monijuan/leetcode_python
CSDN Summary : Simulation volume Leetcode Summary of questions
You can add QQ Group communication :1092754609
leetcode_python.utils See the description on the summary page for details
First brush questions , Then generated by script blog, If there is any mistake, please leave a message , I see it will be revised ! thank you !
边栏推荐
- Win10 cannot operate (delete, cut) files
- Summary of anomaly detection methods
- 【Postman】Monitors 监测API可定时周期运行
- Application of Lie group in gtsam
- [eolink] PC client installation
- [postman] dynamic variable (also known as mock function)
- CoordinatorLayout+NestedScrollView+RecyclerView 上拉底部显示不全
- 模拟卷Leetcode【普通】1061. 按字典序排列最小的等效字符串
- 使用Nacos管理配置
- 對數據安全的思考(轉載)
猜你喜欢
![Buuctf-[gxyctf2019] no dolls (xiaoyute detailed explanation)](/img/0a/054b994b29d4c50ede8b23514cf4ee.jpg)
Buuctf-[gxyctf2019] no dolls (xiaoyute detailed explanation)

GTSAM中李群的運用

曼哈顿距离和-打印菱形

Nodejs realizes the third-party login of Weibo

【Postman】Collections-运行配置之导入数据文件

Request forwarding and redirection
![[postman] collections - run the imported data file of the configuration](/img/85/7ac9976fb09c465c88f376b2446517.png)
[postman] collections - run the imported data file of the configuration

黑猫带你学eMMC协议第10篇:eMMC读写操作详解(read & write)

Redis 核心技术与实战之 基本架构:一个键值数据库包含什么?

IP day 16 VLAN MPLS configuration
随机推荐
Overview of three core areas of Mathematics: geometry
[API interface tool] Introduction to postman interface
G - Supermarket
调用链监控Zipkin、sleuth搭建与整合
浅谈专项测试之弱网络测试
Request forwarding and redirection
Software test interview questions - Test Type
Customize the gateway filter factory on the specified route
【Tera Term】黑猫带你学TTL脚本——嵌入式开发中串口自动化神技能
黑猫带你学UFS协议第18篇:UFS如何配置逻辑单元(LU Management)
数据库隔离级别
ICLR 2022 spotlight | analog transformer: time series anomaly detection method based on correlation difference
LeetCode 732. 我的日程安排表 III
Manage configuration using Nacos
properties文件
Cannot create PoolableConnectionFactory (Could not create connection to database server. 错误
Coordinatorlayout+nestedscrollview+recyclerview pull up the bottom display is incomplete
模拟卷Leetcode【普通】1414. 和为 K 的最少斐波那契数字数目
模拟卷Leetcode【普通】1109. 航班预订统计
模拟卷Leetcode【普通】1062. 最长重复子串