leetcode 38. 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"

二 分析

   easy级别,但是题目看完很难理解,属于绕口令级别:用一个新的字符串描述上一个字符串。就是看一遍不理解 。应该是我英语不好。还不如看数字更直观。

我把1-15 的输出结果打印出来了。

1=1
2=11
3=21
4=1211
5=111221
6=312211
7=13112221
8=1113213211
9=31131211131221
10=13211311123113112211
11=11131221133112132113212221
12=3113112221232112111312211312113211
13=1321132132111213122112311311222113111221131221
14=11131221131211131231121113112221121321132132211331222113112211
15=311311222113111231131112132112311321322112111312211312111322212311322113212221

翻译一下:

从1开始,初始值为1. 即 n=1, 表示1 

当n=2时,解释1,1读作1个 ,表示为11;
当n=3时,解释上一个11,读作2个1,表示为21;
当n=4时,解释上一个21,读作1个2,一个1,表示为1211;
当n=5时,解释上一个1211,读作1个1,1个2,2个1,表示为111221; 

增长的很快,数字都是1,2,3 ,不知道为啥。

很适合用递归的方式。每一次都依赖前一次的结果,要求N,依赖N-1.。。。。直到1.

字符串记录:字符出现次数及字符,判断条件就是下一个不相同,就重新计数,注意边界判断。

  //哈哈,绕口令
	public static String countAndSay(int n) {
		if(n==1){
			return "1";
		}	
		String str ="1";
		for(int i=2;i<=n;i++ ){			
			//遍历字符串
			int count =1;
			String s = "";
			for(int j=0;j<str.length();j++){					
				char c = str.charAt(j);				
				 if(j==str.length()-1||str.charAt(j+1)!=c){						
					s = s+count+c;
					count =1;
				}else{
					count ++;
				}					
			}
			str = s;	
		}
		return str;		
    }

Runtime: 8 ms, faster than 16.06% of Java online submissions for Count and Say.

Memory Usage: 36.1 MB, less than 52.63% of Java online submissions forCount and Say.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值