Isomorphic Strings
来源:互联网 发布:车削编程 编辑:程序博客网 时间:2024/06/05 09:55
题目:
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.
For example,
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:
You may assume both s and t have the same length.
解题思路:
由题意可看出,对于一个Isomorphic字符串,若将其每个字符与其对应的index构成一个hash表。其index项必然相同,此时若把一个hash表中的一个Isomorphic字符串的keys,换做另一个字符串的keys,他们必然相同。
如"egg"
, "add"。则有dic1={'e':[0],'g':[1,2]},dic2={'a':[0],'d':[1,2]} ->dic1.values()==dic2.values()
"foo"
, "bar"。则有dic1={'f':[0],'o':[1,2]},dic2={'a':[1],'b':[0],'r':[2]} ->dic1.values()!=dic2.values()
"ab"
, "ca".则有dic1={'a':[0],'b':[1]},dic2=['a':[1],'c':[0]] ->sorted(dic1)==sorted(dic2)
class Solution:
# @param {string} s
# @param {string} t
# @return {boolean}
def isIsomorphic(self, s, t):
l1,l2 = list(s),list(t)
dic1,dic2 = {},{}
for index,letter in enumerate(l1):
dic1[letter] = dic1.get(letter,[]) + [index]
for index,letter in enumerate(l2):
dic2[letter] = dic2.get(letter,[]) + [index]
return sorted(dic1.values())==sorted(dic2.values())
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- TTS-零基础入门之停止列表中单条语音播报
- 算法竞赛入门经典:第七章 暴力求解法 7.20八数码问题之stl
- 握手定理
- Oracle Database 12c新特性 In-Database Archiving数据库内归档
- caffe caffe.cpp 程序入口分析
- Isomorphic Strings
- SWAP空间不足的处理方法
- 【LeetCode-面试算法经典-Java实现】【05-Longest Palindromic Substring(最大回文字符串)】
- android sharedPreference的用法
- 转:C语言中如何将二维数组作为函数的参数传递
- 【HDOJ 3555】Bomb
- Linux下objdump查看C程序编译后的汇编代码
- Jedis使用
- ThinkAndroid-简单、快速的 Android应用程序的开发框架