- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathStringToPalindrome.java
40 lines (34 loc) Β· 972 Bytes
/
StringToPalindrome.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
packagearray;
importjava.util.HashMap;
importjava.util.Map;
publicclassStringToPalindrome {
publicstaticStringmakePalindrome(Strings) {
HashMap<Character, Integer> map = newHashMap<Character, Integer>();
for (charch : s.toCharArray()) {
if (!map.containsKey(ch)) {
map.put(ch, 1);
} else {
map.put(ch, map.get(ch) + 1);
}
}
StringBuilderans = newStringBuilder(s);
intlow = 0, high = s.length() - 1;
for (Map.Entry<Character, Integer> entries : map.entrySet()) {
if (entries.getValue() == 1) {
ans.setCharAt((ans.length() / 2), entries.getKey());
} else {
ans.setCharAt(low, entries.getKey());
ans.setCharAt(high, entries.getKey());
low++;
high--;
}
}
returnans.toString();
}
publicstaticvoidmain(String[] args) {
Stringstr = "aabbc";
System.out.println(makePalindrome(str));
System.out.println(makePalindrome("aabbccd"));
System.out.println(makePalindrome("abccbar"));
}
}