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"
就是让我们输入n,输出count-and-say序列的第n个字符串。
解决问题,核心是要从最小规模的问题找到一般的规律。
这道题的规律是:第n个字符串是对第n-1个字符串的描述。
问题转化为:得到第一个字符串,以此为基础,迭代产生第n个字符串。
package com.blackfish.bill.algorithm;
public class CountAndSay {
public static String countAndSay(int n) {
if(n <= 0) {
return "";
}
if(n == 1) {
return "1";
}
if(n == 2) {
return "11";
}
//因为使用双指针,需要从第三个字符串开始
String initStr = "11";
int loop = 0;
//迭代产生字符串
while(loop < n - 2) {
initStr = generateStr(initStr);
loop++;
}
return initStr;
}
public static String generateStr(String str) {
if(str == null || str.equals(""))
return "";
int len = str.length();
//双指针
int i = 0;
int j = 1;
//一个数字连续出现的次数,至少出现一次
int charCnt = 1;
String result = "";
while(i < j && j < len) {
if(j == len - 1) {
if(str.charAt(i) == str.charAt(j)) {
charCnt++;
return result + charCnt + str.charAt(i);
} else {
return result + charCnt + str.charAt(i) + "1" + str.charAt(j);
}
}
if(str.charAt(i) == str.charAt(j)) {
//i不动,j移动
j++;
charCnt++;
} else {
result = result + charCnt + str.charAt(i);
charCnt = 1;
//步子迈的有点大
i = j;
j++;
}
}
return result;
}
public static void main(String[] args) {
// String str = "1211";
// String gStr = CountAndSay.generateStr(str);
// System.out.println(gStr);
System.out.println(CountAndSay.countAndSay(7));
}
}