思路:对每个字符串判断连续相同为的个数,然后进行拼接即可。
代码:
public class CountAndSay {
public static void main(String[] args) {
System.out.println(countAndSay(1));
}
public static String countAndSay(int n) {
String s = "1";
StringBuilder sb = null;
int count = 1;
for (int i = 2; i <= n; i++) {
sb=new StringBuilder();
count=1;
for (int j = 0; j < s.length(); j++) {
if (j < s.length() - 1)
if (s.charAt(j) == s.charAt(j + 1))
count++;
else {
sb = sb.append(count).append(s.charAt(j));
count = 1;
}
else
sb=sb.append(count).append(s.charAt(j));
}
s=sb.toString();
//System.out.println(s);
}
return s;
}
}
输出: