-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCountAndSay.java
47 lines (40 loc) · 1.29 KB
/
CountAndSay.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
import java.util.ArrayList;
import java.util.List;
public class CountAndSay {
private static String countAndSay(int number) {
if (number == 1) {
return "1";
}
String previous = countAndSay(number - 1);
List<Pair> pairs = getFrequencies(previous);
StringBuilder result = new StringBuilder();
for (Pair pair : pairs) {
result.append(pair.frequency).append(pair.character);
}
return result.toString();
}
private static List<Pair> getFrequencies(String string) {
char current = string.charAt(0);
int frequency = 0;
List<Pair> result = new ArrayList<>();
for (int index = 0 ; index < string.length() ; index++) {
if (string.charAt(index) != current) {
result.add(new Pair(current, frequency));
frequency = 1;
current = string.charAt(index);
} else {
frequency++;
}
}
result.add(new Pair(current, frequency));
return result;
}
private static class Pair {
final char character;
final int frequency;
Pair(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
}
}