-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC214.java
More file actions
43 lines (33 loc) · 959 Bytes
/
LC214.java
File metadata and controls
43 lines (33 loc) · 959 Bytes
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
36
37
38
39
40
41
42
43
/*
* LC214
*/
import java.util.*;
public class LC214 {
public static String shortestPalindrome(String s) {
int len = s.length();
if (len == 0) {
return s;
}
int left = 0;
for (int i = len - 1; i >= 0; i--) {
if (s.charAt(i) == s.charAt(left)) {
left++;
}
}
if (left == len) {
return s;
}
String nonPan = s.substring(left);
StringBuilder revSuf = new StringBuilder(nonPan).reverse();
return revSuf.append(shortestPalindrome(s.substring(0, left))).append(nonPan).toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the String : ");
String str = sc.nextLine();
System.out.println();
String ans = shortestPalindrome(str);
System.out.println(ans);
sc.close();
}
}