LeetCode 481. 神奇字符串
找规律的题目
class Solution(object):
def magicalString(self, n):
"""
:type n: int
:rtype: int
"""
s = '122'
c = '1'
i = 2
while len(s) < n: # 可以看到规律,每次都是2先行,1后行,他们两个的个数是由之前的数字决定的
s += c * int(s[i])
c = str(3 - int(c))
i += 1
return s[:n].count("1")
C++代码
class Solution {
public:
int magicalString(int n) {
string s = "122";
string c = "1";
int i = 2;
int ans = 1;
while(s.length() < n){
for(int j = 0;j<((int)s[i]-48) && s.length() < n;j++){
s += c;
if(c == "1"){
ans++;
}
}
i += 1;
c = c == "1" ? "2" : "1";
}
return ans;
}
};