481. Magical String ¶ Time: $O(n)$ Space: $O(n)$ C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: int magicalString(int n) { string s = " 122"; for (int i = 3; i <= n; ++i) if (i % 2 == 1) s.append(s[i] - '0', '1'); else s.append(s[i] - '0', '2'); return count(s.begin(), s.begin() + n + 1, '1'); } };