Easy 题目描述看了半天才懂,规律写到注释里了
class Solution {
public String countAndSay(int n) {
if (n <= 0){
return "";
}
String str = "1";
//n=1 1
//n=2 11 (一个1)
//n=3 21(两个1)
//n=4 1211(一个2一个1)
//n=5 111221(一个1一个2两个1)
//n=6 312211(三个1两个2一个1)
for (int i = 1; i < n; i++){
StringBuilder sb = new StringBuilder();
char prev = '.';
int count = 0;
for (int index = 0; index < str.length(); index++){
if (str.charAt(index) == prev || prev == '.'){
count++;
} else {
sb.append(count + String.valueOf(prev));
count = 1;
}
prev = str.charAt(index);
}
sb.append(count + String.valueOf(prev));
str = sb.toString();
}
return str;
}
}