zoukankan      html  css  js  c++  java
  • 外观数列

     迭代:

    class Solution {
    public:
        string countAndSay(int n) {
            string ans ="1";
            n-=1;
            int s_index;//开始的索引
            string temp;
            while(n--)
            {
                temp = "";
                s_index =0;
                for(int i =0;i<(int)ans.size();i++)
                {
                    if(ans[i] != ans[s_index] ) //如果目前的索引不等于开始的索引
                    {
                        temp += (to_string(i-s_index)+ans.substr(s_index,1));
                        s_index = i;
                    }
                }
                //下面处理字符串最后那个数字
                temp += (to_string((int)ans.size()- s_index) + ans.substr(s_index,1));
                ans = temp;
            }
            return ans;
        }
    };

    效率

    递归:

    class Solution {
    public:
        string countAndSay(int n) {
            if(n==1) return "1";
            string ans = countAndSay(n-1);
            int s_index;//开始的索引
            string temp;
            temp = "";
            s_index =0;
            for(int i =0;i<(int)ans.size();i++)
            {
                if(ans[i] != ans[s_index] ) //如果目前的索引不等于开始的索引
                {
                    temp += (to_string(i-s_index)+ans.substr(s_index,1));
                    s_index = i;
                }
            }
            //下面处理字符串最后那个数字
            temp += (to_string((int)ans.size()- s_index) + ans.substr(s_index,1));
            ans = temp;
            return ans;
        }
    };

    题目本意让用递归。可是迭代也可以顺便写出来

  • 相关阅读:
    希望jQuery操作DOM文档,则必须确保DOM载入后开始执行
    Web全栈AngularJS
    Web全栈AngularJS
    Web全栈AngularJS
    KD-Tree
    KD-Tree
    KD-Tree
    KD-Tree
    如何提升自身实力
    如何提升自身实力
  • 原文地址:https://www.cnblogs.com/ranzhong/p/14327428.html
Copyright © 2011-2022 走看看