leetcode 1640. 能否连接形成数组 python

用i计数,用is_find标记是否找到,遍历列表arr,然后在列表pieces中寻找该元素,
如果找到,就对列表arr用切片切出与pieces中小列表长度相同的部分,对两个长度相同的列表进行对比,

如果不相同则返回False,
如果相同则将i加上小列表的长度,将is_find设为True,然后跳出循环;

如果循环结束且没有找到(is_find还是False),就返回False;
如果都能形成连接,则返回True
class Solution:
    def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
        lenth = len(arr)
        i = 0
        while i <= lenth-1:
            is_find = False
            for each in pieces:
                if arr[i] in each:
                    if arr[i: i + len(each)] != each:
                        return False
                    else:
                        i += len(each)
                        is_find = True
                        break
            else:
                if not is_find: return False
        return True

你可能感兴趣的:(leetcode,python,leetcode,算法)