题目链接:count-and-say
/**
*
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.
*
*/
public class CountandSay {
// 18 / 18 test cases passed.
// Status: Accepted
// Runtime: 273 ms
// Submitted: 2 minutes ago
static String countAndSay(int n) {
String s = "1";
for (int i = 1; i < n; i++)
s = countAndSay(s);
return s;
}
static String countAndSay(String str) {
String say = "";
int count = 1;
for (int i = 0; i < str.length() - 1; i++) {
if(str.charAt(i) == str.charAt(i + 1)) count++;
else {
say += count + "" + str.charAt(i);
count = 1;
}
}
say += count + "" + str.charAt(str.length() - 1);
return say;
}
public static void main(String[] args) {
System.out.println(countAndSay(4));
}
}
原文地址:http://blog.csdn.net/ever223/article/details/44524749