```
public int magicalString(int n) {
if (n < 1)
return 0;
if (n < 4)
return 1;
int[] arr = new int[n+2];
int count = 0;
arr[1] = 1;
arr[2] = 2;arr[3] = 2;
int cur1 = 3, cur2 = 4, i;
while (cur2 <= n) {
if (arr[cur1] == 1) {
arr[cur2] = 3 - arr[cur2-1];
cur2++;
} else {
arr[cur2+1] = arr[cur2] = 3 - arr[cur2-1];
cur2 += 2;
}
cur1++;
}
for (i=1;i<=n;i++)
if (arr[i] == 1) {
count++;
}
return count;
}
}
```