```
Re: [Can anyone tell me why I got TLE](it seems time is O(n))
public class Solution {
public int magicalString(int n){
int count = 0;
StringBuilder res = new StringBuilder();
res.append(122);
int index = 2;
while(res.length() <= n){
char c = res.charAt(index);
int len = res.length();
if(c == '1'){
if(res.charAt(len - 1) == '1') res.append(2);
if(res.charAt(len - 1) == '2') res.append(1);
}
else if(c == '2'){
if(res.charAt(len - 1) == '1') res.append(22);
if(res.charAt(len - 1) == '2') res.append(11);
}
index++;
}
for(int i = 0; i < n; i++){
if(res.charAt(i) == '1') count++;
}
return count;
}
```

}