zoukankan      html  css  js  c++  java
  • 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.

    思路:递归+迭代

    第一个思路:递归

    要想求解string(n),就是根据string(n-1)进行求解,所以使用了迭代的方法。

    真正开始判断的时候,定义一个count和一个初始的位置,这种方法已经不止一次的遇到!!!

    只要是相同,那么就下一个,并且count加1,如果不同先是插入几个不同的数字,再插入原来的字符。

    但是要注意最后的一个字符。

    还有一个思路没有看。也贴上来。


    代码:

    class Solution {
    public:
    //https://leetcode.com/problems/count-and-say/
    string countAndSay(int n) {
        //return solution1(n);        //recursive
        return solution2(n);        //iterative
    }
    private:
    string solution1(int n){
        if(n == 2) return "11";
        if(n == 1) return "1";
        string s = solution1(n - 1);
        int count = 1, i;
        char c = s[0];
        string ns;
        for(i = 1; i < s.length(); i++){
            if(s[i] == c) count++;
            else{
                ns += char('0'+count);
                ns += c;
                c = s[i];
                count = 1;
            }
        }
        if(i == s.length()){
            ns += char('0'+count);
            ns += c;
        }
        return ns;
    
    }
    string solution2(int n){
        if(n-- == 1) return "1";
        string cur, pre = "11";
        while(--n){
            int count = 1, i;
            char c = pre[0];
            for(i = 1; i < pre.length(); i++){
                if(pre[i] == c) count++;
                else{
                    cur += char('0'+count);
                    cur += c;
                    c = pre[i];
                    count = 1;
                }
            }
            if(i == pre.length()){
                cur += char('0'+count);
                cur += c;
            }
            pre = cur;
            cur = "";
        }
        return pre;
    }
    };


  • 相关阅读:
    MySQL索引底层的实现
    mysql索引深入优化
    explain详解与索引最佳实践
    (MYSQL)回表查询原理,利用联合索引实现索引覆盖
    为什么重复值高的字段不能建索引(比如性别字段等)
    Spring的事务
    为什么要用Redis?Redis为什么这么快?
    spring AOP
    钩子教程
    钩子教程
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519904.html
Copyright © 2011-2022 走看看