Leetcode初学——外观数列

题目:

这道题其实不难,难得是怎么理解题目的意思

1.  1

2.   11

3.   21

我们就看前三个数

第二个数11是对第一个数的描述“1个1”

第三个数21是对第二个数的描述"2个1"

如此往下推

那我们来看代码:

扫描二维码关注公众号,回复: 9088394 查看本文章
class Solution {
    public String countAndSay(int n) {
        String s = "1";
        while(n>1){
            //加#是为了不用判断结束符
            s += "#";
            String tmp = "";
            int count = 1;
            for(int i=0;i<s.length()-1;i++){
                if(s.charAt(i)==s.charAt(i+1)){
                    count++;
                }else{
                    tmp = tmp+count+s.charAt(i);
                    count = 1;
                }
            }
            s = tmp;
            n--;
        }
        return s;
    }
}

结果如下:

这道题最理想的方法应该是用迭代写,可惜才疏学浅,以后有机会再补上

发布了57 篇原创文章 · 获赞 3 · 访问量 1077

猜你喜欢

转载自blog.csdn.net/qq_39377543/article/details/104121511