Skip to content

Commit e96ff79

Browse files
committed
925. Long Pressed Name
- Language: Python. - Time complexity: O(n+m). - Space complexity: O(1). - Solution: https://leetcode.com/problems/long-pressed-name/editorial/
1 parent 571d9ee commit e96ff79

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

python_solutions/lc_925_long_pressed_name/lc_925.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,33 @@ def isLongPressedNameV1(self, name, typed):
2727
return False
2828

2929
return all(k1 == k2 and v1 <= v2 for (k1, v1), (k2, v2) in zip(g1, g2))
30+
31+
def isLongPressedNameV2(self, name: str, typed: str) -> bool:
32+
# Time complexity: O(n + m). Space complexity: O(1).
33+
# Solution: https://leetcode.com/problems/long-pressed-name/editorial/
34+
# two pointers to the "name" and "typed" string respectively
35+
np, tp = 0, 0
36+
# advance two pointers, until we exhaust one of the strings
37+
while np < len(name) and tp < len(typed):
38+
if name[np] == typed[tp]:
39+
np += 1
40+
tp += 1
41+
elif tp >= 1 and typed[tp] == typed[tp - 1]:
42+
tp += 1
43+
else:
44+
return False
45+
# if there is still some characters left *unmatched* in the origin string,
46+
# then we don't have a match.
47+
# e.g. name = "abc" typed = "aabb"
48+
if np != len(name):
49+
return False
50+
else:
51+
# In the case that there are some redundant characters left in typed
52+
# we could still have a match.
53+
# e.g. name = "abc" typed = "abccccc"
54+
while tp < len(typed):
55+
if typed[tp] != typed[tp - 1]:
56+
return False
57+
tp += 1
58+
# both strings have been consumed
59+
return True

python_solutions/lc_925_long_pressed_name/test_lc_925.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ def test_success_v1(name: str, typed: str, ans: bool, solution: Solution):
3434
assert solution.isLongPressedNameV1(name, typed) is ans
3535

3636

37+
@pytest.mark.parametrize(("name", "typed", "ans"), test_cases)
38+
def test_success_v2(name: str, typed: str, ans: bool, solution: Solution):
39+
assert solution.isLongPressedNameV2(name, typed) is ans
40+
41+
3742
@pytest.fixture
3843
def solution() -> Solution:
3944
return Solution()

0 commit comments

Comments
 (0)