|
1 | 1 | package g1601_1700.s1616_split_two_strings_to_make_palindrome;
|
2 | 2 |
|
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%) |
4 | 4 |
|
5 | 5 | @SuppressWarnings("java:S2234")
|
6 | 6 | public class Solution {
|
7 | 7 | 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); |
17 | 15 | }
|
18 |
| - return isPalindrome(a, i, j) || isPalindrome(b, i, j); |
19 | 16 | }
|
20 | 17 |
|
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--; |
25 | 29 | }
|
26 |
| - return i >= j; |
| 30 | + return true; |
27 | 31 | }
|
28 | 32 | }
|
0 commit comments