38. Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1
is read off as"one 1"
or11
.11
is read off as"two 1s"
or21
.21
is read off as"one 2
, thenone 1"
or1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Thought
這題雖然是 Easy 但讀了好久才懂題目的意思。數列如同題目所說,就是 1, 11, 21, 1211, 111221, ...
一直往後長下去直到長度 n
為止的字串為何。例如 n=5
,數列的演算過程為 1 (n=1), 11, 21 (n=3), 1211, 111221 (n=5)
,所以回傳 111221
為答案。解法為去統計重複出現的數字次數。
Solution
public class Solution {
public String countAndSay(int n) {
if (n <= 0) return null;
String result = "1"; // the 1st element in the sequence
int i = 1;
while (i < n) {
StringBuilder sb = new StringBuilder();
int count = 1;
// compare with the previous string to count the numbers
// if result = "11", j = 0 stands for the count, j = 1 for the number
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == result.charAt(j - 1)) {
count++;
} else {
// if not the same chars such as "21", store the count and the number,
// the reset the count for the next number
sb.append(count);
sb.append(result.charAt(j - 1));
count = 1;
}
}
// to sum up the count of the last number
sb.append(count);
sb.append(result.charAt(result.length() - 1));
result = sb.toString();
i++;
}
return result;
}
}