美文网首页Leetcode
Leetcode 38. Count and Say

Leetcode 38. Count and Say

作者: SnailTyan | 来源:发表于2018-10-09 18:34 被阅读10次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count and Say

2. Solution

class Solution {
public:
    string countAndSay(int n) {
        if(n == 1) {
            return "1";
        }
        string result;
        string current = "1";
        for(int i = 1; i < n; i++) {
            result = statistic(current);
            current = result;
        }
        return result;
    }

private:
    string statistic(string s) {
        string result;
        int count = 1;
        char current = s[0];
        for(int i = 1; i < s.length(); i++) {
            if(current == s[i]) {
                count++;
            }
            else {
                result = result + to_string(count) + current;
                current = s[i];
                count = 1;
            }
        }
        return result + to_string(count) + current;
    }
};

Reference

  1. https://leetcode.com/problems/count-and-say/description/

相关文章

网友评论

    本文标题:Leetcode 38. Count and Say

    本文链接:https://www.haomeiwen.com/subject/xzeyaftx.html