[LeetCode]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
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1。所以输出11。n=3时,因为上次字符是11,有2个1。所以输出21。n=4时。因为上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。
解题思路
说实话,题目第一遍看的时候真没看懂,扯的什么犊子啊。后面看了一下网上的描写叙述,理解了题意,事实上非常easy,能够归结为两点:
- 后一个字符串由前一个字符串生成;
- 对一个字符串连续同样的数进行描写叙述得到下一个字符串,比方连续三个1(即111)用31来表示;
代码
public static String countAndSay(int n) { String result = "1"; String tempStr; char c; int count; if (n == 1) return result; for (int i = 2; i <= n; i++) { int j = result.length() - 1; count = 0; tempStr = ""; c = result.charAt(j); //从后往前循环 while (j >= 0) { //记录连续字符的个数 while (j >= 0 && result.charAt(j) == c) { count++; j--; } tempStr = count + "" + c + "" + tempStr;//m个c="mc" count = 0;//归0。为记录下一个字符做准备 if (j >= 0) { c = result.charAt(j); } } result = tempStr;//得到下一个字符串 } return result; }
版权声明:本文博客原创文章,博客,未经同意,不得转载。