Date: October 31, 2022 10:20 AM
LinkedIn: https://leetcode.cn/problems/magical-string/description/
Title: 神奇字符串
找规律,位运算
参考题解481. 神奇字符串 - 力扣(Leetcode)里面的PPT真的易懂
class Solution:
def magicalString(self, n: int) -> int:
s = [1, 2, 2]
i = 2
while len(s) < n:
# 1: 01
# 2: 10
# 3: 11
# 1^3 =2 2^3 = 1
s += [s[-1] ^ 3] * s[i] # s[i]个 s当前最后一个数与3的异或
i += 1
return s[:n].count(1)
列表添加元素的方法:
直接链接(末尾链接列表)
s = [1, 2, 3]
s += [1] * n # n为添加[1]的个数
append()方法用于在列表的末尾追加元素(可以是单个元素追加,也可以是列表、元组等。)
t = ('bb','cc')
s.append('a')
s.append(t)
s.extend('a')
s.extend(t)
s.insert(index,obj) # 将obj元素插入list1列表中的index个元素位置。
s.insert(1, 'a')
s.insert(2, t)