Skip to content

Commit e5194de

Browse files
committed
Improved 1616
1 parent d9b8f9c commit e5194de

File tree

1 file changed

+20
-16
lines changed
  • src/main/java/g1601_1700/s1616_split_two_strings_to_make_palindrome

1 file changed

+20
-16
lines changed
Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,32 @@
11
package g1601_1700.s1616_split_two_strings_to_make_palindrome;
22

3-
// #Medium #String #Greedy #Two_Pointers #2022_04_13_Time_4_ms_(89.77%)_Space_43.3_MB_(85.58%)
3+
// #Medium #String #Greedy #Two_Pointers #2024_09_04_Time_2_ms_(100.00%)_Space_45.1_MB_(97.99%)
44

55
@SuppressWarnings("java:S2234")
66
public class Solution {
77
public boolean checkPalindromeFormation(String a, String b) {
8-
return check(a, b) || check(b, a);
9-
}
10-
11-
private boolean check(String a, String b) {
12-
int i = 0;
13-
int j = b.length() - 1;
14-
while (j > i && a.charAt(i) == b.charAt(j)) {
15-
++i;
16-
--j;
8+
int n = a.length();
9+
int s = 0;
10+
int e = n - 1;
11+
if (isPalindrome(a, b, s, e, true)) {
12+
return true;
13+
} else {
14+
return isPalindrome(b, a, s, e, true);
1715
}
18-
return isPalindrome(a, i, j) || isPalindrome(b, i, j);
1916
}
2017

21-
private boolean isPalindrome(String s, int i, int j) {
22-
while (j > i && s.charAt(i) == s.charAt(j)) {
23-
++i;
24-
--j;
18+
private boolean isPalindrome(String a, String b, int s, int e, boolean check) {
19+
if (s == e) {
20+
return true;
21+
}
22+
while (s < e) {
23+
if (a.charAt(s) != b.charAt(e)) {
24+
return check
25+
&& (isPalindrome(a, a, s, e, false) || isPalindrome(b, b, s, e, false));
26+
}
27+
s++;
28+
e--;
2529
}
26-
return i >= j;
30+
return true;
2731
}
2832
}

0 commit comments

Comments
 (0)