Leetcode’s daily question
link: 925. Long press to enter the
problem-solving idea: use two pointers name_index and typed_index to traverse two strings respectively, divided into the following three situations:
- 当前两个字符相同并且下一个字符也相同时,同时向后移动一个字符
- 当前两个字符相同并且下一个字符不相同时,typed_index 向后移动一个字符
- 其他情况则为False
Finally, judge whether the size of name_index and typed_index is consistent with the length of the string. There is a little trick, because you want to judge the next character, you can add $ at the end of the character to prevent subscript overflow and judge the last character.
answer:
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
if len(name) == 0:
return True
if len(typed) == 0:
return False
name += "$"
typed += "$"
len_name = len(name) - 1
len_typed = len(typed) - 1
name_index, typed_index = 0, 0
while name_index < len_name and typed_index < len_typed:
if (name[name_index] == typed[typed_index]) and (name[name_index + 1] == typed[typed_index + 1]):
typed_index += 1
name_index += 1
elif (name[name_index] == typed[typed_index]) and (name[name_index + 1] != typed[typed_index + 1]):
typed_index += 1
else:
break
# print(name_index, typed_index)
return name_index == len_name and typed_index == len_typed