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"
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 sequence.
Note: The sequence of integers will be represented as a string.
刚开始题目理解错了,以为求n的转换后的数字,后来仔细一看(1,11,21,1211,111221,。。。)是一个序列,后一个数是前一个的count-and-say表示,题目要求这个序列的第n个数。代码如下:
public class Solution { //当前数字为num求出下一个数字 public String getNextNum(String num){ String re = ""; char[] array = num.toCharArray(); int size = array.length; int count = 0; char temp = array[0]; for(int i=0;i<size;i++){ if(array[i] == temp){ count++; } else{ re = re+count+temp; temp = array[i]; count = 1; } //存在1,11的特殊情况,即无法进入上面else内 if(i == size-1){ re = re+count+temp; } } return re; } public String countAndSay(int n) { ArrayList<String> list = new ArrayList<String>();//顺序存放count-and-say序列 list.add("1"); for(int i=1;i<n;i++){ String next = getNextNum(list.get(i-1)); list.add(next); } return list.get(n-1); } }