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.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
/** * Created by lxw, liwei4939@126.com on 2018/3/6. */ public class L038_Count_and_Say { public String countAndSay(int n){ String init = "1"; for (int i = 1; i< n; i++){ init = countAndSay(init); } return init; } String countAndSay(String str){ char[] arr = str.toCharArray(); String res = ""; int index = 1; int count = 1; char last = arr[0]; for (; index < arr.length; index++){ if (arr[index] == last){ count++; }else { res += "" + count + last; count = 1; last = arr[index]; } } res += "" + count + last; return res; } public static void main(String[] args){ L038_Count_and_Say tmp = new L038_Count_and_Say(); int num = 4; System.out.println(tmp.countAndSay(num)); } }