Description#
Given a string s
, return true
if it is possible to split the string s
into three non-empty palindromic substrings. Otherwise, return false
.
A string is said to be palindrome if it the same string when reversed.
Example 1:
Input: s = "abcbdd"
Output: true
Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
Example 2:
Input: s = "bcbddxy"
Output: false
Explanation: s cannot be split into 3 palindromes.
Constraints:
3 <= s.length <= 2000
s
consists only of lowercase English letters.
Solutions#
Solution 1#
1
2
3
4
5
6
7
8
9
10
11
12
| class Solution:
def checkPartitioning(self, s: str) -> bool:
n = len(s)
g = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = s[i] == s[j] and (i + 1 == j or g[i + 1][j - 1])
for i in range(n - 2):
for j in range(i + 1, n - 1):
if g[0][i] and g[i + 1][j] and g[j + 1][-1]:
return True
return False
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| class Solution {
public boolean checkPartitioning(String s) {
int n = s.length();
boolean[][] g = new boolean[n][n];
for (var e : g) {
Arrays.fill(e, true);
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = s.charAt(i) == s.charAt(j) && (i + 1 == j || g[i + 1][j - 1]);
}
}
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
if (g[0][i] && g[i + 1][j] && g[j + 1][n - 1]) {
return true;
}
}
}
return false;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| class Solution {
public:
bool checkPartitioning(string s) {
int n = s.size();
vector<vector<bool>> g(n, vector<bool>(n, true));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = s[i] == s[j] && (i + 1 == j || g[i + 1][j - 1]);
}
}
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
if (g[0][i] && g[i + 1][j] && g[j + 1][n - 1]) {
return true;
}
}
}
return false;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| func checkPartitioning(s string) bool {
n := len(s)
g := make([][]bool, n)
for i := range g {
g[i] = make([]bool, n)
for j := range g[i] {
g[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
g[i][j] = s[i] == s[j] && (i+1 == j || g[i+1][j-1])
}
}
for i := 0; i < n-2; i++ {
for j := i + 1; j < n-1; j++ {
if g[0][i] && g[i+1][j] && g[j+1][n-1] {
return true
}
}
}
return false
}
|