Count and Say LeetCode solution in Java

1
class Solution {
2
public String countSay(int n, String[] mapper) {
3
if (n == 1) return mapper[1];
4
else {
5
String say = "";
6
if (mapper[n - 1] != null) say += mapper[n - 1];
7
else say += countSay(n - 1, mapper);
8
String count = "";
9
int cache = Integer.parseInt(say.substring(0, 1));
10
int cntr = 1;
11
if (say.length() < 2) {
12
count += "1" + Integer.toString(cache);
13
} else {
14
for (int i = 1; i < say.length(); i++) {
15
if (cache == Integer.parseInt(say.substring(i, i + 1))) {
16
cntr++;
17
if (i == say.length() - 1) {
18
count += Integer.toString(cntr) + Integer.toString(cache);
19
cntr = 1;
20
}
21
} else {
22
count += Integer.toString(cntr) + Integer.toString(cache);
23
if (i < say.length() - 1) {
24
cache = Integer.parseInt(say.substring(i, i + 1));
25
cntr = 1;
26
} else if (i == say.length() - 1) {
27
count += "1" + say.substring(i, i + 1);
28
}
29
}
30
}
31
}
32
mapper[n] = count;
33
return mapper[n];
34
}
35
}
36

37
public String countAndSay(int n) {
38
String mapper[] = new String[n + 1];
39
mapper[1] = "1";
40
return countSay(n, mapper);
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0