zoukankan      html  css  js  c++  java
  • [leetcode]count and say2

    class Solution {
    public:
        //when see str, return count and say of str
        string process(const string& str){
            if (str == "")
                return "";
    
            int l = 0;
            int r = 0;
            int count = 0;
            string result = "";
            for (; r < str.length(); ){
                if (str[r] == str[l]){
                    count++;
                    r++;
                }
                else{//每当发现str[r]和str[l]不一样时,将l到r-1的append到result
                    char tmp[5];
                    memset(tmp, 0, 5);
                    sprintf(tmp, "%d%d", count, str[l] - '0');
                    result.append(tmp);
                    count = 0;
                    l = r;
                }
            }
            char tmp[5];
            memset(tmp, 0, 5);
            sprintf(tmp, "%d%c", count, str[l]);
            result.append(tmp);
    
            return result;
        }
    
        string countAndSay(int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (n < 1)
                return "";
    
            string str = "1";
            if (n == 1)
                return str;
            
            for (int i = 1; i < n; i++){
                string tmp = process(str);
                str.assign(tmp);
            }
    
            return str;
        }
    };

    EOF

  • 相关阅读:
    取三级分销上下级用户id
    Map集合
    Log4j
    异常
    逻辑运算符
    变量
    变量名命名规则
    命名法
    Nessus
    Nmap扫描工具
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2839947.html
Copyright © 2011-2022 走看看