-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path181_Google_Split_String_Into_Plaindromes.py
More file actions
executable file
·44 lines (28 loc) · 1.11 KB
/
Copy path181_Google_Split_String_Into_Plaindromes.py
File metadata and controls
executable file
·44 lines (28 loc) · 1.11 KB
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
39
40
41
42
43
44
"""
This problem was asked by Google.
Given a string, split it into as few strings as possible such that each string is a palindrome.
For example, given the input string racecarannakayak, return ["racecar", "anna", "kayak"].
Given the input string abc, return ["a", "b", "c"].
"""
# The max number of palindromes can would be the length of the
# string itself if no palindromes are found
# Min palindrome can be 1 if th string itself is a palindrome.
# start with all letters are palindrome and try reducing them.
def return_min_palindromes(s):
palindromes = []
is_palindrome = lambda x: x == x[::-1]
def helper(string, left_over=""):
if len(string) == 0:
return
if is_palindrome(string):
palindromes.append(string)
helper(left_over, "")
else:
helper(string[:-1], string[-1] + left_over)
helper(s)
return palindromes
if __name__ == '__main__':
print(return_min_palindromes('abc'))
print(return_min_palindromes('racecarannakayak'))
print(return_min_palindromes('abaana'))
print(return_min_palindromes('abaaba'))