Count and Say

本文详细解析了计数与说序列算法的工作原理及Java实现过程,通过实例展示了如何生成给定序列号对应的序列。

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.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

题目意思是:

如果是1,则读作 一个1,可以写成 11。
如果是11,则读作 两个1,可以写成 21。
如果是21,则读作 一个2和一个1,可以写成 1211。
如果是1211,则读作 一个1,一个2,两个1,可以写成 111221。
如果是111221,则读作 三个1,两个2,一个1,可以写成 312211。
...
以此类推

Java实现:

 1 public class Solution {
 2     public String countAndSay(int n) {
 3     
 4         if (n == 1) return new String("1");
 5         if (n == 2) return new String("11");
 6         
 7         String preString = new String("11"); // 每次保存前一个序列
 8         
 9         for (int count = 3; count <= n; count ++) {
10         // for循环控制第n个序列
11             int len = preString.length();
12             int i = 0;
13             int j = i + 1;
14             String tempString = ""; // 每次保存当前序列
15             while (i < len) {
16             // while循环根据当前序列长度控制当前序列
17                 char s1 = preString.charAt(i);
18                 char s2 = 0;
19                 int k = 1;
20                 // 处理当前序列最后一位
21                 if (j < len)
22                     s2 = preString.charAt(j);
23                 else {
24                     tempString += "1" + s1;
25                     break;
26                 }
27                 
28                 if (s1 == s2) {
29                 // 寻找当前序列连续相同数字并用 k 统计
30                     while (s1 == preString.charAt(j)) {
31                         j++;
32                         k++;
33                         if (j == len) break;
34                     }
35                     
36                     String tempChar = String.valueOf(s1);
37                     tempString += k + tempChar;
38                     i = j;
39                     j = i + 1;
40                 } else {
41                 // 无连续相同数字
42                     tempString += "1" + s1;
43                     i = j;
44                     j = i + 1; 
45                 }
46                 
47             }
48             preString = tempString;
49         }
50         
51         return preString;
52   }
53     
54     public static void main(String[] args) {
55         Solution solu = new Solution();
56         String s = solu.countAndSay(9);
57         System.out.println(s);
58     }
59 }

 

转载于:https://www.cnblogs.com/yanjliu/p/4045091.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值