1. What I learned
ord()
It is used when a character is converted to a ASCII code.
print(ord('a'))
print(ord('z'))
# 97
# 122
2. Code
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
output = []
for word in words:
if len(word) != len(pattern): # I don't have to check if the words and patterns don't match.
continue
mapping = {} # Dictionary to store letters and patterns
ch = [] # List to store the characters I have verified so far
flag = True
for i in range(len(pattern)):
if pattern[i] not in mapping:
if word[i] not in ch: # It's when a letter of the word first appears
mapping[pattern[i]] = word[i]
ch.append(word[i])
else: # It's when the letter of the word is mapped differently in the dictionary
flag = False
break
else:
if mapping[pattern[i]] != word[i]: # This is when the letter of the word is different from that already stored in the dictionary
flag = False
break
if flag == True:
output.append(word)
return output
3. Result
Runtime : 24 ms(98.44%), Memory usage : 14.1 MB(88.46%)
(Runtime can be different by a system even if it is a same code.)