-
Notifications
You must be signed in to change notification settings - Fork 68
/
makeAStringPalindrome.java
42 lines (41 loc) · 1.31 KB
/
makeAStringPalindrome.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
36
37
38
39
40
41
42
public class makeStringPalindrome {
public static int add(String str){
int start=0, end= str.length()-1;
int len=end,insertAt=0;
int count=0;
StringBuilder strNew= new StringBuilder(str);
while(start<end){
if(str.charAt(start)==str.charAt(end)){
start++;
end--;
}
else{
if(count==0){
if(end<str.length()-1){
for(int i=end+1; i<str.length(); i++){
strNew.insert(0,str.charAt(i));
insertAt++;
}
}
else {
strNew.insert(0, str.charAt(end));
insertAt++;
}
}
else{
strNew.insert(insertAt++,str.charAt(end));
}
count++;
start=0;
end= --len;
}
}
System.out.println("New palindromic string: "+ strNew);
return count;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String str= sc.next();
System.out.println("Min num of characters add in front of String: "+ add(str));
}
}