2022-11-01 1181

leetcode 1181 前后拼接
优化
1,只存头,不存尾巴
2,用find
3,j+1 在第二个循环中优化了,但也难理解了

class Solution:
    def beforeAndAfterPuzzles(self, p: List[str]) -> List[str]:
        h=defaultdict(list)
        s=set()
        c=' '
        for i,v in enumerate(p):
            j=v.find(c)
            w=v if j==-1 else v[:j]
            h[w].append(i)
        for i,v in enumerate(p):
            j=v.rfind(c)+1
            tou=v[:j]
            t=v[j:]
            if t in h:
                for x in h[t]:
                    if x!=i:s.add(tou+p[x])
        w=list(s)
        w.sort()
        return w
#https://leetcode.cn/problems/before-and-after-puzzle/solution/by-jerryluan-q6tt/

你可能感兴趣的:(2022-11-01 1181)