File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed
Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change @@ -1315,3 +1315,4 @@ mod s1739_building_boxes;
13151315mod s1742_maximum_number_of_balls_in_a_box;
13161316mod s1743_restore_the_array_from_adjacent_pairs;
13171317mod s1744_can_you_eat_your_favorite_candy_on_your_favorite_day;
1318+ mod s1745_palindrome_partitioning_iv;
Original file line number Diff line number Diff line change 1+ /**
2+ * [1745] Palindrome Partitioning IV
3+ *
4+ * Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.
5+ * A string is said to be palindrome if it the same string when reversed.
6+ *
7+ * Example 1:
8+ *
9+ * Input: s = "abcbdd"
10+ * Output: true
11+ * Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
12+ *
13+ * Example 2:
14+ *
15+ * Input: s = "bcbddxy"
16+ * Output: false
17+ * Explanation: s cannot be split into 3 palindromes.
18+ *
19+ *
20+ * Constraints:
21+ *
22+ * 3 <= s.length <= 2000
23+ * s consists only of lowercase English letters.
24+ *
25+ */
26+ pub struct Solution { }
27+
28+ // problem: https://leetcode.com/problems/palindrome-partitioning-iv/
29+ // discuss: https://leetcode.com/problems/palindrome-partitioning-iv/discuss/?currentPage=1&orderBy=most_votes&query=
30+
31+ // submission codes start here
32+
33+ impl Solution {
34+ pub fn check_partitioning ( s : String ) -> bool {
35+ let n = s. len ( ) ;
36+ let mut dp = vec ! [ vec![ false ; n] ; n] ;
37+ let s = s. chars ( ) . collect :: < Vec < char > > ( ) ;
38+
39+ for i in 0 ..n {
40+ dp[ i] [ i] = true ;
41+ }
42+
43+ for k in 1 ..n {
44+ for i in 0 ..n {
45+ if i + k >= n {
46+ continue ;
47+ }
48+ dp[ i] [ i + k] = if s[ i] == s[ i + k] { true } else { false } ;
49+ if k > 2 {
50+ dp[ i] [ i + k] = dp[ i] [ i + k] && dp[ i + 1 ] [ i + k - 1 ] ;
51+ }
52+ }
53+ }
54+
55+ for i in 0 ..n {
56+ for j in i + 2 ..n {
57+ if dp[ 0 ] [ i] && dp[ i + 1 ] [ j - 1 ] && dp[ j] [ n - 1 ] {
58+ return true ;
59+ }
60+ }
61+ }
62+
63+ false
64+ }
65+ }
66+
67+ // submission codes end
68+
69+ #[ cfg( test) ]
70+ mod tests {
71+ use super :: * ;
72+
73+ #[ test]
74+ fn test_1745_example_1 ( ) {
75+ let s = "abcbdd" . to_string ( ) ;
76+
77+ let result = true ;
78+
79+ assert_eq ! ( Solution :: check_partitioning( s) , result) ;
80+ }
81+
82+ #[ test]
83+ fn test_1745_example_2 ( ) {
84+ let s = "bcbddxy" . to_string ( ) ;
85+
86+ let result = false ;
87+
88+ assert_eq ! ( Solution :: check_partitioning( s) , result) ;
89+ }
90+ }
You can’t perform that action at this time.
0 commit comments