0481. Magical String
Description
**Input:** n = 6
**Output:** 3
**Explanation:** The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.**Input:** n = 1
**Output:** 1ac
Last updated
**Input:** n = 6
**Output:** 3
**Explanation:** The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.**Input:** n = 1
**Output:** 1Last updated
class Solution {
public int magicalString(int n) {
// edge cases
if (n == 0) return 0;
if (n < 3) return 1;
int[] nums = new int[n];
nums[0] = 1; nums[1] = nums[2] = 2;
int i = 3, cnt1 = 1, countIdx = 2, curr = 1;
while (i < n) {
int count = nums[countIdx++];
while (i < n && count-- > 0) {
nums[i] = curr;
if (nums[i] == 1) cnt1++;
i++;
}
curr = 3 - curr; // flip 1 and 2
}
return cnt1;
}
}
/*
1) build the array, when nums[i] is 1 cnt++; 2) flip curr between 1 and 2 each time, get count from array;
*/