思路:
1. 1,开始
2. 1解释成1个1,得结果11
3. 11解释成2个1,得结果21;
4. 21解释成1个2,1个1,得结果1211
从第一个字符开始,如果后面的与该字符相同,则count++,不然就把该字符的count和该字符本身添加上。
public String countAndSay(int n) {
String s = "1";
for (int i = 1; i < n; i++) {
s = countChar(s);
}
return s;
}
public String countChar(String s) {
StringBuilder stringBuilder = new StringBuilder();
char c = s.charAt(0);
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
} else {
stringBuilder.append(count);
stringBuilder.append(c);
count = 1;
c = s.charAt(i);
}
}
stringBuilder.append(count);
stringBuilder.append(c);
return stringBuilder.toString();
}
网友评论