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

    description:

    就是看前面那个数有几个几,然后写一串。
    Note:

    Example:

    The count-and-say sequence is the sequence of integers with the first five terms as following:
    
    1.     1
    2.     11
    3.     21
    4.     1211
    5.     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.
    

    answer:

    class Solution {
    public:
        string countAndSay(int n) {
            if (n < 0) return "";
            string res = "1";
            for (int i = 1; i < n; i++) {
                string newres = "";
                for (int k = 0; k < res.size(); ++k) {
                    int cnt = 1;
                    while(k + 1 < res.size() && res[k] == res[k +1]){
                        cnt += 1;
                        ++k;
                    }
                    newres += to_string(cnt) + res[k]; 
                }
                res = newres;
            }
            return res;
        }
    };
    

    relative point get√:

    • to_string() c++中string类的内置函数

    hint :

  • 相关阅读:
    旅行计划
    两只塔姆沃斯牛
    迷宫
    异或序列
    异或之和
    素数个数
    SAC E#1
    [JSOI2010]Group 部落划分 Group
    [USACO12FEB]附近的牛Nearby Cows
    [HNOI2008]Cards
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11124815.html
Copyright © 2011-2022 走看看