-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountAndSay.java
48 lines (41 loc) · 1.06 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
48
package integer;
/**
* @author Shogo Akiyama
* Solved on 12/25/2019 and 05/29/2020
* Time: 12m
*
* 38. Count and Say
* https://leetcode.com/problems/count-and-say/
* Difficulty: Easy
*
* Approach: Dynamic Programming (Bottom up)
* Runtime: 7 ms, faster than 30.83% of Java online submissions for Count and Say.
* Memory Usage: 36 MB, less than 52.63% of Java online submissions for Count and Say.
*
* Time Complexity: O(k*n)
* Space Complexity: O(n)
* Where n is the given number and k is the length of the largest sequence till n
*
* @see IntegerTest#testCountAndSay()
*/
public class CountAndSay {
public String countAndSay(int n) {
String[] dp = new String[n];
dp[0] = "1";
for (int i = 1; i < n; i++) {
String prev = dp[i - 1];
dp[i] = "";
int count = 1;
for (int j = 1; j < prev.length(); j++) {
if (prev.charAt(j - 1) == prev.charAt(j)) {
count++;
} else {
dp[i] += count + "" + prev.charAt(j - 1);
count = 1;
}
}
dp[i] += count + "" + prev.charAt(prev.length() - 1);
}
return dp[n - 1];
}
}