Skip to content

Commit a9e57d4

Browse files
Palindrome using deque (#803)
* Add method using deque * updated tests for is_palindrome.py deque
1 parent 6e7e1f2 commit a9e57d4

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

algorithms/strings/is_palindrome.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
we define empty string as valid palindrome.
1212
"""
1313
from string import ascii_letters
14+
from collections import deque
1415

1516

1617
def is_palindrome(s):
@@ -85,3 +86,20 @@ def is_palindrome_stack(s):
8586
if s[i] != stack.pop():
8687
return False
8788
return True
89+
90+
# Variation 4 (using deque)
91+
def is_palindrome_deque(s):
92+
s = remove_punctuation(s)
93+
deq = deque()
94+
for char in s:
95+
deq.appendleft(char)
96+
97+
equal = True
98+
99+
while len(deq) > 1 and equal:
100+
first = deq.pop()
101+
last = deq.popleft()
102+
if first != last :
103+
equal = False
104+
105+
return equal

tests/test_strings.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
group_anagrams,
99
int_to_roman,
1010
is_palindrome, is_palindrome_reverse,
11-
is_palindrome_two_pointer, is_palindrome_stack,
11+
is_palindrome_two_pointer, is_palindrome_stack, is_palindrome_deque,
1212
is_rotated, is_rotated_v1,
1313
license_number,
1414
make_sentence,
@@ -195,6 +195,11 @@ def test_is_palindrome_stack(self):
195195
self.assertTrue(is_palindrome_stack("Otto"))
196196
self.assertFalse(is_palindrome_stack("house"))
197197

198+
def test_is_palindrome_deque(self):
199+
# 'Otto' is a old german name.
200+
self.assertTrue(is_palindrome_deque("Otto"))
201+
self.assertFalse(is_palindrome_deque("house"))
202+
198203

199204
class TestIsRotated(unittest.TestCase):
200205
"""[summary]

0 commit comments

Comments
 (0)