38. Count and Say

一、Description:

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"


二、Ideas:

    1.题意解读:

       本题目的是实现数字的口语化转换,例如:当字符串为“1”时,读作“1个1”,所以需要转换成:“11”;同样,“11”读作“2个1”,所以需要转换成“21”;那么,“21”则被读作“1个2,1个1”,即“1211”,以此类推,找到第n个字符串。

     2.思路:
         在了解题意后,本题的思路就比较简单了。首先,给定一个初始字符串“1”,然后,根据给定的n遍历,每次遍历都需要从头遍历当前字符串,检查相同字符的个数,并设定一个mark,用于标记一次计数的结束,只有计数结束才可以更新字符串,这里需要注意两个临界条件:1.最后一个字符和前一个字符相同,这时,由于计数并没有结束,但显然下一次就结束遍历了,所以需要人为将计数结束并更新字符串;2.最后一个字符和前一个字符不相同,此时由于上一次计数已经结束,字符串已经更新,但显然这之后就会退出遍历了,所以需要将最后一个字符更新到字符串里。
三、Code:

class Solution {
    public String countAndSay(int n) {
        String str="1";
        for(int i=1;i<n;i++){
        	int len=str.length();
        	int num=1;
        	int mark=0;
        	String mid=new String();
        	if(len==1) {
        		mid="1"+String.valueOf(str.charAt(0));
        	}
        	for(int j=0;j+1<len;j++){
        		if(str.charAt(j)==str.charAt(j+1)){
        			num++;
        			mark=0;
        		} 
        		else mark=1;
        		if(mark==1){
        			mid=mid+String.valueOf(num)+String.valueOf(str.charAt(j));
        			if(j+1==len-1) mid=mid+"1"+String.valueOf(str.charAt(j+1));
        			num=1;
        		}
        		else if(j+1==len-1){
        			mid=mid+String.valueOf(num)+String.valueOf(str.charAt(j));
        			num=1;
        		}
        		
        	}
        	str=mid;
        }
        return str;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值