Count and Say 数数并打印 @LeetCode

题目:

数数并打印

题目比较不直观,这里的描述比较好一些  http://www.careercup.com/question?id=4425679

"Count and Say problem" Write a code to do following: 
n String to print 
0 1 
1 1 1    因为前面一行有1个1
2 2 1     因为前面一行有2个1
3 1 2 1 1  因为前面一行有1个2和1个1
... 
Base case: n = 0 print "1" 
for n = 1, look at previous string and write number of times a digit is seen and the digit itself. In this case, digit 1 is seen 1 time in a row... so print "1 1" 
for n = 2, digit 1 is seen two times in a row, so print "2 1" 
for n = 3, digit 2 is seen 1 time and then digit 1 is seen 1 so print "1 2 1 1" 
for n = 4 you will print "1 1 1 2 2 1" 

Consider the numbers as integers for simplicity. e.g. if previous string is "10 1" then the next will be "1 10 1 1" and the next one will be "1 1 1 10 2 1"


思路:

遍历,每次对前面的string进行分析,输出

package Level2;

/**
 * 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.
 *
 */
public class S38 {

	public static void main(String[] args) {
		System.out.println(countAndSay(6));
	}
	
	public static String countAndSay(int n) {
		
		if(n == 1){
			return "1";
		}
		
		String s = "1";
		StringBuffer ret = new StringBuffer();
		int cnt = 0;
		int round = 0;			// round是迭代多少次
		int i;
		while(++round < n){
			cnt = 1;
			ret.setLength(0);
			for(i=1; i<s.length(); i++){
				if(s.charAt(i) == s.charAt(i-1)){		// 重复的值,继续计数
					cnt++;
				}else{			// 有新的值出现,记录到ret
					ret.append(cnt).append(s.charAt(i-1));
					cnt = 1;		// 重置cnt
				}
			}
			ret.append(cnt).append(s.charAt(i-1));
			s = ret.toString();	// 更新s
		}
		return ret.toString();
	}

}



public class Solution {
    public String countAndSay(int n) {
        String s = "1";
        
        for(int i=1; i<n; i++) {
            int cnt = 1;
            StringBuilder tmp = new StringBuilder();
            for(int j=1; j<s.length(); j++) {
                if(s.charAt(j) == s.charAt(j-1)) {
                    cnt++;
                } else {
                    tmp.append(cnt).append(s.charAt(j-1));
                    cnt = 1;
                }
            }
            tmp.append(cnt).append(s.charAt(s.length()-1));
            s = tmp.toString();
        }
        
        return s;
    }
}

注意到这题如果用 tmp.append(cnt+s.charAt(j-1)); 则会超时



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值