leetcode no 38 count and say

1. 题目

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.

2. 思路

暴力求解,从第一个数一直算到第n个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class  {
public String countAndSay(int n) {
String s = "1";
if(n == 1){
return s;
}
for(int i=1;i<n;i++){
int count = 1;
char first = s.charAt(0);
String tmp = "";
for(int j=1;j<s.length();j++){
if(s.charAt(j-1) == s.charAt(j)){
count++;
}else{
tmp = tmp+count+s.charAt(j-1);
count = 1;
}
}
tmp = tmp+count+s.charAt(s.length()-1);
s = tmp;
count = 1;
}
return s;
}
}