-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode1328_BreakingAPalindrome.java
More file actions
45 lines (33 loc) · 1.21 KB
/
Copy pathleetcode1328_BreakingAPalindrome.java
File metadata and controls
45 lines (33 loc) · 1.21 KB
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
44
45
public class leetcode1328_BreakingAPalindrome {
public String breakPalindrome(String palindrome) {
int index = 0;
String str;
char[] chars = palindrome.toCharArray();
//Sample cases
//aa -> ab
//bb -> bc
//aaa -> aab
//case when there is only single character
if(palindrome.length() ==1)
return "";
//change the first character to 'a' when any other letter is found
for(Character ch : palindrome.toCharArray()){
//make the change in the first possbile character
if(palindrome.length()%2!=0 && index==palindrome.length()/2)
continue;
if(ch != 'a' ){
chars[index] = 'a';
return String.valueOf(chars);
}
index++;
}
//change the last character to b
chars[palindrome.length()-1] = (char)(palindrome.charAt(palindrome.length()-1)+1);
return String.valueOf(chars);
}
public static void main(String[] args) {
leetcode1328_BreakingAPalindrome obj = new leetcode1328_BreakingAPalindrome();
String res = obj.breakPalindrome("a");
System.out.println(res);
}
}