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

    数出来,确实很符合字面意思。比如 “1” 念 “一个一” 那么得出的就是 “11”; “11” 念 “两个 1” 那么得出的就是 “21”; “21” 念出来是 “一个二一个一” 那么 “1211”......

    我的代码很笨拙,是这样的:

    string countAndSay(int n) {
        if (n < 1){
            return string();
        }
        
        string result("1");
        char current = '';
        size_t count = 0;
        
        auto saveCountAndNum = [&](string& s)
        {
            s.append(to_string(count));
            s.push_back(current);
        };
        
        function<string(const string&)> say;
        say = [&](const string& s)
        {
            string newStr;
            current = s.front();
            count = 0;
            
            for (auto it = s.cbegin(); it != s.cend(); ++it){
                if ((it + 1) == s.cend() && *it != current){
                    if (count != 0){
                        saveCountAndNum(newStr);
                    }
                    newStr.push_back('1');
                    newStr.push_back(*it);
                }
                else if ((it + 1) == s.cend() && *it == current){
                    ++count;
                    saveCountAndNum(newStr);
                }
                else if (*it != current){
                    saveCountAndNum(newStr);
                    current = *it;
                    count = 1;
                }
                else{
                    ++count;
                }
            }
            return newStr;
        };
        for (int i = 1; i != n; ++i){
            result = say(result);
        }
        return result;
    }
  • 相关阅读:
    CSRF的安全问题
    preg_replace
    反汇编:虚函数表
    12.Proxy
    JS中的this
    11.Set 和 Map数据结构
    10.symbol
    9.对象的扩展
    test
    ES5支持的方法
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4752298.html
Copyright © 2011-2022 走看看