-
Notifications
You must be signed in to change notification settings - Fork 0
/
1745. Palindrome Partitioning IV.java
35 lines (32 loc) · 1.26 KB
/
1745. Palindrome Partitioning IV.java
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
class Solution {
public boolean checkPartitioning(String s) {
int length = s.length();
boolean[][] isPalindrome = new boolean[length][length];
for (int i = 0; i < length; i++)
isPalindrome[i][i] = true;
for (int i = 1; i < length; i++)
isPalindrome[i - 1][i] = s.charAt(i - 1) == s.charAt(i);
for (int i = length - 3; i >= 0; i--) {
for (int j = i + 2; j < length; j++)
isPalindrome[i][j] = isPalindrome[i + 1][j - 1] && s.charAt(i) == s.charAt(j);
}
int maxFirst = length - 3, maxSecond = length - 2;
for (int i = 0; i <= maxFirst; i++) {
if (isPalindrome[0][i]) {
for (int j = i + 1; j <= maxSecond; j++) {
if (isPalindrome[i + 1][j] && isPalindrome[j + 1][length - 1])
return true;
}
}
}
return false;
/* also working, but a little lower efficiency
for (int i = 0; i <= maxFirst; i++) {
for (int j = i + 1; j <= maxSecond; j++) {
if (isPalindrome[0][i] && isPalindrome[i + 1][j] && isPalindrome[j + 1][length - 1])
return true;
}
}
*/
}
}