leetcode python 030 Substring with Concatenation of All Words

时间:2023-03-09 16:59:24
leetcode python 030 Substring with Concatenation of All Words

## 您将获得一个字符串s,以及一个长度相同单词的列表。
## 找到s中substring(s)的所有起始索引,它们只包含所有单词,
## eg:s: "barfoothefoobarman" words: ["foo", "bar"]
## return [0,9].

def find_sub(s,words):
    m,n,o=len(s),len(words[0]),len(words)
    for i in words:
        assert len(i)==n,'words length is not equal'
    def ch(l,n):
        return set([l[i:i+3] for i in range(0,len(l),n)])
    q=set(words)
    return [i for i in range(m-n*o+1) if ch(s[i:i+n*o],n)==q]

s,words="barfoothefoobarman",["foo", "bar"]
print(find_sub(s,words))