134.Count and Say
题目:
The count-and-say sequence is the sequence of integers with the first five terms as following:
count-and-say序列是整数序列,前五个术语如下:
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
.
1. 1
2. 11
3. 21
4. 1211
5. 111221
1被读作“1”或11。
11被读作“两个1”或21。
21被读作“一个2,然后一个1”或1211。
Given an integer n, generate the nth term of the count-and-say sequence.
给定整数n,生成count-and-say序列的第n项。
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 class Solution { 2 public String countAndSay(int n) { 3 StringBuilder curr=new StringBuilder("1"); 4 StringBuilder prev; 5 int count; 6 char say; 7 for(int i=1;i<n;i++){ 8 prev=curr; 9 curr=new StringBuilder(); 10 count=1; 11 say=prev.charAt(0); 12 13 for(int j=1;j<prev.length();j++){ 14 if(prev.charAt(j)!=say){ 15 curr.append(count).append(say); 16 count=1; 17 say=prev.charAt(j); 18 } 19 else count++; 20 } 21 curr.append(count).append(say); 22 } 23 return curr.toString(); 24 } 25 }
详解:
对于序列1,11,21,1211......
前一个数,找出相同元素的个数,把个数和该元素存到一起。如1有一个1就是11;11有2个1,就是21;21有一个2,一个1,就是1211