题目描述:
https://leetcode.com/problems/count-and-say/
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211
解答:
package com.jack.algorithm;
/**
* create by jack 2019/6/30
*
* @author jack
* @date: 2019/6/30 16:19
* @Description:
* 递归计算,输入n,按规则计算n-1的序列
*/
public class CountAndSay {
/**
* 38-题目描述
* https://leetcode.com/problems/count-and-say/
*
* @param n
* @return
*/
public static String countAndSay(int n) {
String s = "1";
for(int i = 1; i < n; i++) {
//递归分解,n=n-1序列,n-1=n-2序列
s=say(s);
}
return s;
}
public static String say(String s) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
int count = 1;
while( i+1<s.length() && s.charAt(i) == s.charAt(i+1)) {
i++;
//相同字符的个数
count++;
}
sb.append(count);
sb.append(s.charAt(i));
}
return sb.toString();
}
public static void main(String[] args) {
String s = countAndSay(10);
System.out.println("s="+s);
}
}
源码: