C++ Greedy + Counting O(N) Time O(1) space
See my latest update in repo LeetCode\n\n\n## Solution 1. Greedy + Counting\n\nStore frequency of characters in int cnt[26].\n\nWe pick characters in batches. I
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n\n## Solution 1. Greedy + Counting\n\nStore frequency of characters in `int cnt[26]`.\n\nWe pick characters in batches. In each batch, we pick the first character from `z` to `a` whose `cnt` is positive with the following caveats:\n1. If the current character is the same as the one used in the previous batch, we need to skip it.\n2. On top of case 1, if the `cnt` of the character used in the previous batch is positive, then we can only fill a single character in this batch.\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-281/problems/construct-string-with-repeat-limit/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    string repeatLimitedString(string s, int limit) {\n        int cnt[26] = {};\n        string ans;\n        for (char c : s) cnt[c - \'a\']++;\n        while (true) {\n            int i = 25;\n            bool onlyOne = false;\n            for (; i >= 0; --i) {\n                if (ans.size() && i == ans.back() - \'a\' && cnt[i]) { // the character of our last batch still has some count left, so we only insert a single character in this batch\n                    onlyOne = true;\n                    continue;\n                }\n                if (cnt[i]) break; // found a character with positive count, fill with this character\n            }\n            if (i == -1) break; // no more characters to fill, break;\n            int fill = onlyOne ? 1 : min(cnt[i], limit);\n            cnt[i] -= fill;\n            while (fill--) ans += \'a\' + i;\n        }\n        return ans;\n    }\n};\n```
[]