-
Notifications
You must be signed in to change notification settings - Fork 2
/
Result.java
61 lines (51 loc) · 1.48 KB
/
Result.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package hackrank.algorithm.string.anagram;
import java.util.Arrays;
/**
* @see <a href="https://www.hackerrank.com/challenges/anagram">Anagram</a>
*/
public class Result {
/**
* @param s value to check for anagram
* @return minimum number of characters to change {@code s} to an anagram. -1 if not possible.
*/
public static int anagram(String s) {
if (s.length() % 2 == 1) {
return -1;
}
int middle = s.length() / 2;
char[] first = s.substring(0, middle).toCharArray();
char[] second = s.substring(middle).toCharArray();
Arrays.sort(first);
Arrays.sort(second);
int changes = 0;
int freebiesFirst = 0;
int freebiesSecond = 0;
int i = 0;
int j = 0;
while (i < first.length && j < second.length) {
if (first[i] == second[j]) {
i++;
j++;
continue;
}
if (first[i] < second[j]) {
i++;
if (freebiesFirst > 0) {
freebiesFirst--;
} else {
changes++;
freebiesSecond++;
}
} else {
j++;
if (freebiesSecond > 0) {
freebiesSecond--;
} else {
changes++;
freebiesFirst++;
}
}
}
return changes;
}
}