zoukankan      html  css  js  c++  java
  • LeetCode题解38.Count and Say

    38. 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.

    My Thought

    理解题目理解了半天。。。
    好吧,大致意思是,第一个数字是“1”(字符串的形式)。从第二个数字开始,字符串按照前一个字符串的读法决定。比如,前一个是“1”,那么就是1个“1”,于是第二个字符串是“11”,依次类推。
    一个递归解决问题。
    伪代码:

    PROCEDURE countAndSay(n)
    	if n = 1
        	return "1"
        else
       		// 获取前一个字符串
        	preString = countAndSay(n-1)
            // 按规则读字符串,作为返回串、
            return read(preString)
    

    Code(C++ 0ms)

    class Solution {
    public:
        string countAndSay(int n) {
            if(n==1)
                return "1";
            string pre = countAndSay(n-1);
            // read rule
            pre+='#';
            string ret="",temp="";
            int num = 1;
            char ch=pre[0];
            for(int i=1;i<pre.size();++i){
                if(pre[i]!=ch){
                    temp+=('0'+num);
                    temp+=ch;
                    ret.append(temp);
                    temp="";
                    ch=pre[i];
                    num=0;
                }
                num+=1;
            }
            return ret;
    
        }
    };
    

    最后0ms ACC 镇啊,激动(虽然很ez23333
    0ms

    题解在我的github上会第一时间更新,有兴趣的可以star一下

  • 相关阅读:
    HTML区块
    HTML表单
    JavaScript 表单验证
    HTML头部
    JavaScript
    设计模式—单例模式的六种写法
    new
    new
    new
    new
  • 原文地址:https://www.cnblogs.com/HolyShine/p/6954065.html
Copyright © 2011-2022 走看看