Skip to content

Commit 32a1ff9

Browse files
Update is_palindrome.py (TheAlgorithms#8022)
1 parent 9f041e9 commit 32a1ff9

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

strings/is_palindrome.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,24 @@ def is_palindrome(s: str) -> bool:
1616
# Since punctuation, capitalization, and spaces are often ignored while checking
1717
# palindromes, we first remove them from our string.
1818
s = "".join(character for character in s.lower() if character.isalnum())
19-
return s == s[::-1]
19+
# return s == s[::-1] the slicing method
20+
# uses extra spaces we can
21+
# better with iteration method.
22+
23+
end = len(s) // 2
24+
n = len(s)
25+
26+
# We need to traverse till half of the length of string
27+
# as we can get access of the i'th last element from
28+
# i'th index.
29+
# eg: [0,1,2,3,4,5] => 4th index can be accessed
30+
# with the help of 1st index (i==n-i-1)
31+
# where n is length of string
32+
33+
for i in range(end):
34+
if s[i] != s[n - i - 1]:
35+
return False
36+
return True
2037

2138

2239
if __name__ == "__main__":

0 commit comments

Comments
 (0)