forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Palindrom_Check.py
40 lines (30 loc) · 949 Bytes
/
Palindrom_Check.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Solution 1
# O(n^2) time | O(n) space
def is_palindrome(string):
reversed_string = ""
for i in reversed(range(len(string))):
reversed_string += string[i]
return string == reversed_string
# Solution 2
# O(n) time | O(n) space
def is_palindrome(string):
reversed_chars = []
for i in reversed(range(len(string))):
reversed_chars.append(string[i])
return string == "".join(reversed_chars)
# Solution 3. A tail-recursive solution
# O(n) time | O(n) space
def is_palindrome(string, i = 0):
j = len(string) - 1 - i
return True if i >= i else string[i] == string[j] and is_palindrome(string, i + 1)
# Solution 4
# O(n) time | O(1) space
def is_palindrome(string):
left_index = 0
right_index = len(string) - 1
while left_index < right_index:
if string[left_index] != string[right_index]:
return False
left_index += 1
right_index -= 1
return True