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;
    }
    };


  • 相关阅读:
    2016.10.15先占坑
    2016.10.11先占坑
    2016.10.13先占坑
    2016.10.7先占坑
    main()里面为什么要放String[] args
    对于一个给定的正整数 n ,请你找出一共有多少种方式使 n 表示为若干个连续正整数的和,要求至少包括两个正整数。
    求两个数的最大公约数的三种算法总结
    C++
    Dev-c5.11的使用
    客户端和服务器端的交互(未完待续)
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519904.html
Copyright © 2011-2022 走看看