LeetCode解题报告-- 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.
点击解题:Count and Say

分析:题意是要求通过程序生成一组符合题意要求的字符串,
题目难度不高,基本思路是:以n为例,直接从左向右扫描n-1字符串,计算出现相同数字的个数 ,直至扫描结束!示意图如下:初始:count = 1,,每遇到数字相同,count++,然后将count转为字符串或字符类型 + 当前数组字符 以此为规律找出nth字符串。
这里写图片描述

java代码: Accepted

public class Solution {
    public String countAndSay(int n) {
       String newS = "1";
       int count = 1;
       int i = 1;
       while(i < n){
           String s = newS;
           newS = "";
           for(int j = 0;j < s.length();j ++){
                if( (j + 1) < s.length() && s.charAt(j) == s.charAt(j + 1)){
                    count ++;
                }else{
                    newS = newS + count + s.charAt(j);
                    count = 1;
                }
            }
            i ++;
       }
       return newS;
    }
}

python代码 Accepted

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        i = 1
        count = 1
        newS = "1"

        while i < n:
            s= newS
            newS = ""

            for j in range(len(s)):
                if((j + 1) < len(s) and s[j] == s[j + 1]):
                    count = count + 1
                else:
                    newS = newS + str(count) + s[j]
                    count = 1
            i = i + 1
        return newS
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值