LC.P481[神奇字符串] 方法一:模拟12345678910111213141516class Solution { public int magicalString(int n) { char[] s = new char[n + 2]; s[0] = 1; s[1] = s[2] = 2; char c = 2; for (int i = 2, j = 3; j < n; ++i) { c ^= 3; // 1^3=2, 2^3=1 s[j++] = c; if (s[i] == 2) s[j++] = c; } int ans = 0; for (int i = 0; i < n; ++i) ans += 2 - s[i]; return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$