38. Count and Say

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

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        for (int i = 1; i < n; i++) {
            string t;
            for (int j = 1, c = 1; j <= res.length(); j++) {
                if (j == res.length() || res[j] != res[j-1]) {
                    t += to_string(c) + res[j-1];
                    c = 1;
                }
                else 
                    c++;
            }
            res = t;
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9056454.html