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, 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数的特征,没找见,尴尬。最直观的想法就是一点点从第一个数据往下算过去,这样的时间复杂度肯定是比较大的,但暴力的方法总能解决问题。计算的核心问题是如何根据第i个count and say数c[i]得到第i+1个count and say数c[i+1],最简单的办法就是从头对c[i]的每位数进行计数,如果相同那么count加一,如果不同将这位数及count值推入结果。最后进行循环即可。(或者迭代效果更好?)最终代码如下:
class Solution { public String countAndSay(int n) { String s="1";//初始化 for(int i=1;i<n;i++) { s=change(s);//循环下去 } return s; } static String change(String s)//对于一个输入的序列得到下一个序列 { StringBuilder res=new StringBuilder(); int length=s.length(); int count=1; char temp1=s.charAt(0); for (int i=1;i<length;i++) { if(s.charAt(i)==temp1)//判断相同计数 count++; else//判断不同,缓存 { res.append(count); res.append(temp1); temp1=s.charAt(i); count=1; } } res.append(count);//当长度为1和最后一位的数据存入缓存 res.append(temp1); return res.toString(); } }
最后消耗时间只超过38%的提交者,表示这个算法意料之内远远没有达到最优。
时间: 2024-10-11 00:32:11