LintCode python 小白-简单题-638-Strings Homomorphism
来源:互联网 发布:景安域名转入 编辑:程序博客网 时间:2024/05/20 03:43
题目:Given two strings s and t, determine if they are isomorphic.Two strings are isomorphic if the characters in s can be replaced to get t.All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
样例
Given s = “egg”, t = “add”, return true.
Given s = “foo”, t = “bar”, return false.
Given s = “paper”, t = “title”, return true.
题目解析:给出两个字符串s和t,它们同构,(顺序相同,长度相同,结构相同)。
思路:使用字典进行映射关系的判断。主要是建立映射关系,和重复项关系判断。
- 新建一个放s[i]为键,t[i]为值的字典dict和一个字符串string存放满足映射的t
- 判断s[i]是否为dict的键,若是则代表dict中该键的值为t[i]
- 若不是则先判断一个问题,t[i]是否是前面t值重复的,这时候就需要与字符串进行比较,判断是否是前面出现的t[0:t-1],若存在,则代表s与t映射关系出现错误(如果存在映射关系,s[i]不在dict,代表t[i]的值不应该存在string),return False
- 将s[i]、t[i]放在字典中,t[i]放在字符串string中
- 跳转到2
代码如下:
class Solution: # @param {string} s a string # @param {string} t a string # @return {boolean} true if the characters in s # can be replaced to get t or false def isIsomorphic(self, s, t): # Write your code here if len(s)<0 or len(t)<0 or len(s)!=len(t): return False dict={} #建立一个空的字典 string='' #建立一个空的字符串 for i in range(len(s)): if s[i] not in dict.keys(): #判断s的第i-1个值是否为字典的健 if t[i] in string: return False dict[s[i]]=t[i] string=string+t[i] else: if dict[s[i]]!=t[i]: return False return True
阅读全文
1 0
- LintCode python 小白-简单题-638-Strings Homomorphism
- lintcode(638)Strings Homomorphism
- LintCode之Strings Homomorphism
- Strings Homomorphism
- Strings Homomorphism
- Strings Homomorphism
- Strings Homomorphism
- LintCode python 小白-简单题-627最长回文串
- LintCode python 小白-简单题-569各位相加
- LintCode python 小白-简单题-413-反转整数
- LintCode python 小白-简单题-22平面列表
- LintCode python 小白-简单题-2 尾部的0
- LintCode python 小白-简单题-445余弦相识度
- LintCode python 小白-简单题-646 First Position Unique Character
- LintCode python 小白-简单题-548两数组的交Ⅱ
- LintCode python 小白-简单题-457经典二分查找问题
- LintCode python 小白-简单题-423有效的括号序列
- LintCode python 小白1
- 动态树
- java实现定时任务的三种方法
- 解决ScrollView嵌套ListView进入界面不在顶部的问题
- 数据类型转换之 char* 与 int
- 读文件的工具
- LintCode python 小白-简单题-638-Strings Homomorphism
- oracle SQL查询优化
- grafana
- java自动拆装箱知识点
- Maven新建webapp项目报错Could not resolve artifact org.apache.maven.archetypes:maven-archetype-webapp:pom:R
- Hibernate知识点总结
- 小知识点总结记录(一)
- 加盟开店 介绍
- ubuntu下安装theano环境