一 题目
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 where 1 ≤ n ≤ 30, 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"
二 分析
easy级别,但是题目看完很难理解,属于绕口令级别:用一个新的字符串描述上一个字符串。就是看一遍不理解 。应该是我英语不好。还不如看数字更直观。
我把1-15 的输出结果打印出来了。
1=1
2=11
3=21
4=1211
5=111221
6=312211
7=13112221
8=1113213211
9=31131211131221
10=13211311123113112211
11=11131221133112132113212221
12=3113112221232112111312211312113211
13=1321132132111213122112311311222113111221131221
14=11131221131211131231121113112221121321132132211331222113112211
15=311311222113111231131112132112311321322112111312211312111322212311322113212221
翻译一下:
从1开始,初始值为1. 即 n=1, 表示1
当n=2时,解释1,1读作1个 ,表示为11;
当n=3时,解释上一个11,读作2个1,表示为21;
当n=4时,解释上一个21,读作1个2,一个1,表示为1211;
当n=5时,解释上一个1211,读作1个1,1个2,2个1,表示为111221;
增长的很快,数字都是1,2,3 ,不知道为啥。
很适合用递归的方式。每一次都依赖前一次的结果,要求N,依赖N-1.。。。。直到1.
字符串记录:字符出现次数及字符,判断条件就是下一个不相同,就重新计数,注意边界判断。
//哈哈,绕口令
public static String countAndSay(int n) {
if(n==1){
return "1";
}
String str ="1";
for(int i=2;i<=n;i++ ){
//遍历字符串
int count =1;
String s = "";
for(int j=0;j<str.length();j++){
char c = str.charAt(j);
if(j==str.length()-1||str.charAt(j+1)!=c){
s = s+count+c;
count =1;
}else{
count ++;
}
}
str = s;
}
return str;
}
Runtime: 8 ms, faster than 16.06% of Java online submissions for Count and Say.
Memory Usage: 36.1 MB, less than 52.63% of Java online submissions forCount and Say.