1. Description
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, generate the nth term of the count-and-say sequence.
Note
Each term of the sequence of integers will be represented as a string.
2. Example
Example 1
Input: 1
Output: "1"
Example 2
Input: 4
Output: "1211"
3. Code
public class LeetCode0038 {
public String countAndSay(int n) {
if (n < 1) {
return null;
}
StringBuilder sb = new StringBuilder();
String str = "1";
for (int i = 2; i <= n; i++) {
char pre = str.charAt(0);
int count = 1;
for (int j = 1; j < str.length(); j++) {
char c = str.charAt(j);
if (c != pre) {
sb.append(count).append(pre);
count = 1;
pre = c;
} else {
count++;
}
}
sb.append(count).append(pre);
str = sb.toString();
sb.setLength(0);
}
return str;
}
public static void main(String[] args) {
LeetCode0038 leetcode = new LeetCode0038();
System.out.println(leetcode.countAndSay(5));
}
}
Comments | NOTHING