# Leetcode023--计数和说出来

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时输出字符串1；n=2时，数上次字符串中的数值个数，因为上次字符串有1个1，所以输出11；n=3时，由于上次字符是11，有2个1，所以输出21；n=4时，由于上次字符串是21，有1个2和1个1，所以输出1211。依次类推，写个countAndSay(n)函数返回字符串。

## 五、程序

```package code;

public class LeetCode26{
public static void main(String args[]){
System.out.println("Res4 = "+countAndSay(4));
System.out.println("Res5 = "+countAndSay(5));
}

public static String countAndSay(int n){
String res = "1";
//第一个是一，所以是从第二个开始的
for(int i = 2; i <= n; i++){
res = SpeakNum(res);
}
return res;
}

public static String SpeakNum(String str){

StringBuffer buf = new StringBuffer(100);
int count = 1;

//从左向右进行识别
for(int i = 1; i < str.length(); i++){
//如果有两个相等的就计数加一
if(str.charAt(i) == str.charAt(i - 1)){
count++;
}else{
buf.append(count);
buf.append(str.charAt(i-1));
count = 1;
}
}

//将最后的部分加上
buf.append(count);
buf.append(str.charAt(str.length() - 1));
return buf.toString();
}

}
```

--------------------output------------------------
```Res4 = 1211
Res5 = 111221```