-
Notifications
You must be signed in to change notification settings - Fork 459
/
Palindrome_Partitioning_Min_Cuts.py
59 lines (49 loc) · 1.73 KB
/
Palindrome_Partitioning_Min_Cuts.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Solution 1
# O(n^3) time | O(n^2) space
def palindromePartitioningMinCuts(string):
palindromes = [[False for i in string] for j in string]
for i in range(len(string)):
for j in range(i, len(string)):
palindromes[i][j] = isPalindrome(string[i:j + 1])
cuts = [float('inf') for i in len(string)]
for i in range(len(string)):
if palindromes[0][i]:
cuts[i] = 0
else:
cuts[i] = cuts[i - 1] + 1
for j in range(1, i):
if palindromes[j][i] and cuts[j - 1] + 1 < cuts[i]:
cuts[i] = cuts[j - 1] + 1
return cuts[-1]
def isPalindrome(string):
leftIdx = 0
rightIdx = len(string) - 1
while leftIdx < rightIdx:
if string[leftIdx] != string[rightIdx]:
return False
leftIdx += 1
rightIdx -= 1
return True
# Solution 2
# O(n^2) time | O(n^2) space
def palindromePartitioningMinCuts(string):
palindromes = [[False for i in string] for j in string]
for i in range(len(string)):
palindromes[i][i] = True
for length in range(2, len(string) + 1):
for i in range(0, len(string) - length + 1):
j = i + length -1
if length == 2:
palindromes[i][j] = string[i] == string[j]
else:
palindromes[i][j] = string[i] == string[j] and palindromes[i + 1][j - 1]
cuts = [float('-inf') for i in string]
for i in range(len(string)):
if palindromes[0][i]:
cuts[i] = 0
else:
cuts[i] = cuts[i - 1] + 1
for j in range(1, i):
if palindromes[j][i] and cuts[j - 1] + 1 < cuts[i]:
cuts[i] = cuts[j - 1] + 1
return cuts[-1]