1
+ # O(N^3) time | O(N^2) space
2
+
3
+
4
+ def palindromePartitionMinCuts (string ):
5
+ palindromes = [[False for _ in string ] for _ in string ]
6
+ for i in range (len (string )):
7
+ for j in range (i , len (string )):
8
+ palindromes [i ][j ] = isPalindrome (string [i : j + 1 ])
9
+ cuts = [float ("inf" ) for _ in string ]
10
+ for i in range (len (string )):
11
+ if palindromes [0 ][i ]:
12
+ cuts [i ] = 0
13
+ else :
14
+ cuts = cuts [i - 1 ] + 1
15
+ for j in range (1 , i ):
16
+ if palindromes [j ][i ] and cuts [j - 1 ] + 1 < cuts [i ]:
17
+ cuts [i ] = cuts [j - 1 ] + 1
18
+ return cuts [- 1 ]
19
+
20
+
21
+ def isPalindrome (string ):
22
+ leftIdx = 0
23
+ rightIdx = len (string ) - 1
24
+ while leftIdx < rightIdx :
25
+ if string [leftIdx ] != string [rightIdx ]:
26
+ return False
27
+ leftIdx += 1
28
+ rightIdx -= 1
29
+ return True
30
+
31
+
32
+ # O(N^2) time | O(N^2) space
33
+
34
+
35
+ def palindromePartitionMinCuts (string ):
36
+ palindromes = [[False for _ in string ] for _ in string ]
37
+ for i in range (len (string )):
38
+ palindromes [i ][i ] = True
39
+ for length in range (2 , len (string ) + 1 ):
40
+ for i in range (0 , len (string ) - length + 1 ):
41
+ j = i + length - 1
42
+ if length == 2 :
43
+ palindromes [i ][j ] = string [i ] == string [j ]
44
+ else :
45
+ palindromes [i ][j ] = string [i ] == string [j ] and palindromes [i + 1 ][j - 1 ]
46
+ cuts = [float ("inf" ) for _ in string ]
47
+ for i in range (len (string )):
48
+ if palindromes [0 ][i ]:
49
+ cuts [i ] = 0
50
+ else :
51
+ cuts = cuts [i - 1 ] + 1
52
+ for j in range (1 , i ):
53
+ if palindromes [j ][i ] and cuts [j - 1 ] + 1 < cuts [i ]:
54
+ cuts [i ] = cuts [j - 1 ] + 1
55
+ return cuts [- 1 ]
0 commit comments