Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
\
Mysolution:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
mag_map = collections.defaultdict(int)
for l in magazine:
mag_map[l] += 1
for r in ransomNote:
if r in mag_map and mag_map[r] > 0:
mag_map[r] -= 1
else:
return False
return True
Given two strings s and t, determine if they are isomorphic.
Two strings s and t 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.
\
Solution:
s 和 t 建立两个映射字典,用来记录字符之间的对应关系。(c1, c2) 时,需要检查:
c1 之前已经在 s_map 中出现过,那么它应该始终映射到相同的 c2;c2 之前在 t_map 中出现过,它也应该始终映射回相同的 c1。class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s_map, t_map = {}, {}
for c1, c2 in zip(s, t):
if ((c1 in s_map and s_map[c1] != c2) or
c2 in t_map and t_map[c2] != c1):
return False
s_map[c1] = c2
t_map[c2] = c1
return True
Given a pattern and a string s, find if s follows the same pattern.