原题
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.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
中文题意
本题为:计数-内容,最开始给出的字符串内容为“1”,根据第一次的字符串,得到第二次的字符串为“11”,含义为:“1”个“1”,根据第二次的字符串,得到第三次的字符串为“21”,含义为:两个一.....依次类推,即下一行的内容根据上一行的字符串内容决定:数字1的个数 数字1 数字2的个数 数字2...的拼接。
分析
每一行的确定必须来自于上一行的结果,如果求第n行的情况,必须从第1行向后推导得出。
首先,对于第n行的确定,必须使用上一行的结果,我们使用pre集合记录上一行的结果,curr记录当前的结果,pre = curr的操作保证pre记录的更新。
java代码
class Solution {
public String countAndSay(int n) {
List<Integer> pre = new ArrayList<Integer>();
List<Integer> curr = new ArrayList<Integer>();
pre.add(new Integer(1));
int count = 1;//count初始值设置为1是为了后面遍历上一层元素时,下标为0的元素不再单独遍历
StringBuffer res = new StringBuffer();
if(n==0 || n==1){
return pre.get(0).toString();
}
//求解n>1的情况
for(int i = 2; i <= n; i++){//从第二行开始,向后推导到第n行
curr = new ArrayList<Integer>();//存储每一行的结果
for(int m=1;m<pre.size();m++){//遍历上一行数据,m的起始值为1
if(pre.get(m - 1).intValue() == pre.get(m).intValue()){
count++;
}else{
curr.add(new Integer(count));
curr.add(pre.get(m-1));
count = 1;
}
}
curr.add(new Integer(count));
curr.add(pre.get(pre.size() - 1));
pre = curr;//当前行的结果作为下一行计算的input
count = 1;
}
for(Integer num:curr){
res.append(num);
}
return res.toString();
}
}