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, 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"

这个题目有一点让人难以理解~其实是这样的,以题目给出的1到5为例,1对应1;2则是对前一个数1进行count-and-say,是一个1,也就是11;3是对前一个数2进行count-and-say,是两个1,也就是21;4是对前一个数3进行count-and-say,是一个2,一个1,也就是1211;5是对前一个数4进行count-and-say,也就是1个1,1个2,两个1,111221.

高票做法:
public class Solution {
    public String countAndSay(int n) {
	    	StringBuilder curr=new StringBuilder("1");
	    	StringBuilder prev;
	    	int count;
	    	char say;
	        for (int i=1;i<n;i++){
	        	prev=curr;
	 	        curr=new StringBuilder();       
	 	        count=1;
	 	        say=prev.charAt(0);
	 	        
	 	        for (int j=1,len=prev.length();j<len;j++){
	 	        	if (prev.charAt(j)!=say){
	 	        		curr.append(count).append(say);
	 	        		count=1;
	 	        		say=prev.charAt(j);
	 	        	}
	 	        	else count++;
	 	        }
	 	        curr.append(count).append(say);
	        }	       	        
	        return curr.toString();
        
    }
}
其实就是从1开始,依次推到n。值得注意的是里面用了StringBuilder,而不是string,简单来讲,string是不可变对象,每次对string进行更改其实都是生成了一个新的string,并将指针指向该string。所以经常改变内容的字符串最好不要用 String ,因为每次生成对象都会对系统性能产生影响,特别当内存中无引用对象多了以后, JVM 的 GC 就会开始工作,那速度是一定会相当慢的。而如果是使用 StringBuffer 类则结果就不一样了,每次结果都会对 StringBuffer 对象本身进行操作,而不是生成新的对象,再改变对象引用。java.lang.StringBuilder被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。两者的方法基本相同。String,StringBuffer与StringBuilder的区别??


我的做法,用到了递归,速度太慢~

class Solution {
public String countAndSay(int n) {
if(n==1)
return "1";

String ns=countAndSay(n-1);
String result="";
int count=1;
if(ns.length()==1)
return "11";

for(int i=1;i<ns.length();i++){
if(ns.charAt(i)==ns.charAt(i-1)){
count++;
if(i==ns.length()-1)
result=result+count+ns.charAt(i);
}
else
{
result=result+count+ns.charAt(i-1);
count=1;
if(i==ns.length()-1)
result=result+count+ns.charAt(i);
}
}
return result;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值