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.
Example 1:
1 | Input: s = "egg", t = "add" |
209 Word Pattern
用到的语法:
python string split() method
1 | txt = "welcome to the jungle" |
solution 1: Two Hash Maps
pattern
: ‘abba’
str
: ‘dog cat fish dog’
pattern_dict
= {a:0, b:1}
str_dict
= {dog:0, cat:1, fish:2}
1 | class Solution: |
solution 2: Single Index Hash Map
pattern
: ‘abba’
str
: ‘dog cat fish dog’
map_index
={ a:0 , dog:0 , b:1 , cat:1 , fish:2}
index of ‘b’ and index of ‘fish’ are NOT the same. Returns False
.
1 | class Solution: |
关于这里为什么要把char和string 区别开来:
如果不区别的话,
pattern=”abc”
str=”b c a”
Differentiating between character and string: In Python there is no separate char
type. And for cases such as:
pattern: ‘abba’ str: ‘b a a b’
Using the same hash map will not work properly. A workaround is to prefix each character in pattern
with “char_” and each word in str
with “word_”.
solution 3:
1 | def wordPattern(self, pattern, str): |
205 Isomorphic Strings
209 和 205 同思路,同方法
Solution 1:
s
=”foo”
t
=”bar”
check={ f:true, o:true}
dic={ f:b, o:a}
When i =index2
o and r return false, since o is already in check
1 | class Solution: |
solution 3:
1 | return len(set(zip(s, t))) == len(set(s)) == len(set(t)) |
python zip() 用法