38. Count and Say (Easy)
https://leetcode.com/problems/count-and-say/
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
Solutions
class Solution {
public String countAndSay(int n) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "1");
map.put(2, "11");
map.put(3, "21");
map.put(4, "1211");
map.put(5, "111221");
if (map.keySet().contains(n)) {
return map.get(n);
}
for (int i = 6; i <= n; i++) {
String pre = map.get(i - 1);
map.put(i, resolve(pre));
}
return map.get(n);
}
private String resolve(String s) {
String ans = "";
int count = 1;
char pre = s.charAt(0);
// 111,22,1
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) != pre) {
// ans="", count=3, pre=1
ans += count + "" + pre;
// reset count
count = 0;
}
// increase count of same char
count++;
pre = s.charAt(i);
}
ans += count + "" + pre;
return ans;
}
}