File tree Expand file tree Collapse file tree 3 files changed +12
-9
lines changed
solution/0200-0299/0214.Shortest Palindrome Expand file tree Collapse file tree 3 files changed +12
-9
lines changed Original file line number Diff line number Diff line change @@ -271,8 +271,9 @@ class Solution:
271
271
``` java
272
272
class Solution {
273
273
public String shortestPalindrome (String s ) {
274
- char [] t = (s + " #" + new StringBuilder (s). reverse(). toString() + " $" ). toCharArray();
275
- int n = t. length();
274
+ String rev = new StringBuilder (s). reverse(). toString();
275
+ char [] t = (s + " #" + rev + " $" ). toCharArray();
276
+ int n = t. length;
276
277
int [] next = new int [n];
277
278
next[0 ] = - 1 ;
278
279
for (int i = 2 , j = 0 ; i < n;) {
@@ -284,7 +285,7 @@ class Solution {
284
285
next[i++ ] = 0 ;
285
286
}
286
287
}
287
- return new StringBuilder (s . substring(next[n - 1 ])) . reverse() . substring(0 , s. length() - next[n - 1 ]) + s;
288
+ return rev . substring(0 , s. length() - next[n - 1 ]) + s;
288
289
}
289
290
}
290
291
```
Original file line number Diff line number Diff line change @@ -252,8 +252,9 @@ class Solution:
252
252
``` java
253
253
class Solution {
254
254
public String shortestPalindrome (String s ) {
255
- char [] t = (s + " #" + new StringBuilder (s). reverse(). toString() + " $" ). toCharArray();
256
- int n = t. length();
255
+ String rev = new StringBuilder (s). reverse(). toString();
256
+ char [] t = (s + " #" + rev + " $" ). toCharArray();
257
+ int n = t. length;
257
258
int [] next = new int [n];
258
259
next[0 ] = - 1 ;
259
260
for (int i = 2 , j = 0 ; i < n;) {
@@ -265,7 +266,7 @@ class Solution {
265
266
next[i++ ] = 0 ;
266
267
}
267
268
}
268
- return new StringBuilder (s . substring(next[n - 1 ])) . reverse() . substring(0 , s. length() - next[n - 1 ]) + s;
269
+ return rev . substring(0 , s. length() - next[n - 1 ]) + s;
269
270
}
270
271
}
271
272
```
Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public String shortestPalindrome (String s ) {
3
- char [] t = (s + "#" + new StringBuilder (s ).reverse ().toString () + "$" ).toCharArray ();
4
- int n = t .length ();
3
+ String rev = new StringBuilder (s ).reverse ().toString ();
4
+ char [] t = (s + "#" + rev + "$" ).toCharArray ();
5
+ int n = t .length ;
5
6
int [] next = new int [n ];
6
7
next [0 ] = -1 ;
7
8
for (int i = 2 , j = 0 ; i < n ;) {
@@ -13,6 +14,6 @@ public String shortestPalindrome(String s) {
13
14
next [i ++] = 0 ;
14
15
}
15
16
}
16
- return new StringBuilder ( s . substring ( next [ n - 1 ])). reverse () .substring (0 , s .length () - next [n - 1 ]) + s ;
17
+ return rev .substring (0 , s .length () - next [n - 1 ]) + s ;
17
18
}
18
19
}
You can’t perform that action at this time.
0 commit comments