File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ Given a string s, partition s such that every substring of the partition is a palindrome.
3
+
4
+ Return all possible palindrome partitioning of s.
5
+
6
+ For example, given s = "aab",
7
+ Return
8
+
9
+ [
10
+ ["aa","b"],
11
+ ["a","a","b"]
12
+ ]
13
+ '''
14
+
15
+ class Solution (object ):
16
+ def partition (self , s ):
17
+ """
18
+ :type s: str
19
+ :rtype: List[List[str]]
20
+ """
21
+ if not s :
22
+ return [[]]
23
+ result = []
24
+ for i in range (len (s )):
25
+ if self .isPalindrome (s [:i + 1 ]):
26
+ for r in self .partition (s [i + 1 :]):
27
+ result .append ([s [:i + 1 ]] + r )
28
+ return result
29
+
30
+ def isPalindrome (self , s ):
31
+ return s == s [::- 1 ]
32
+
33
+
34
+ if __name__ == "__main__" :
35
+ assert Solution ().partition ("aab" ) == [
36
+ ["a" , "a" , "b" ],
37
+ ["aa" , "b" ]
38
+ ]
Original file line number Diff line number Diff line change
1
+ '''
2
+ Given a string s, partition s such that every substring of the partition is a palindrome.
3
+
4
+ Return the minimum cuts needed for a palindrome partitioning of s.
5
+
6
+ For example, given s = "aab",
7
+ Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
8
+ '''
9
+
10
+ class Solution (object ):
11
+ def minCut (self , s ):
12
+ """
13
+ :type s: str
14
+ :rtype: List[List[str]]
15
+ """
16
+ n = len (s )
17
+ dp = [0 for __ in range (n )]
18
+ isPal = [[False for __ in range (n )] for __ in range (n )]
19
+ for i in range (n ):
20
+ m = i
21
+ for j in range (i + 1 ):
22
+ if s [j ] == s [i ] and (j + 1 > i - 1 or isPal [j + 1 ][i - 1 ]):
23
+ isPal [j ][i ] = True
24
+ m = 0 if j == 0 else min (m , dp [j - 1 ] + 1 )
25
+ dp [i ] = m
26
+ return dp [- 1 ]
27
+
28
+
29
+ if __name__ == "__main__" :
30
+ assert Solution ().minCut ("aab" ) == 1
You can’t perform that action at this time.
0 commit comments