爆内存:
# encoding = utf-8
# 开发者:xxx
# 开发时间: 15:01
# "Stay hungry,stay foolish."
class Solution(object):
def findSubstring(self, s, words):
import itertools
res = []
len(words)
permutations_lst = list(itertools.permutations(words, len(words)))
for i in permutations_lst:
str1 = ''.join(i)
s1 = s
for _ in range(len(s)+1):
index = s1.find(str1)
if index != -1:
if index not in res:
res.append(index)
s1 = s1[:index]+"_"+s1[index+1:]
res.sort()
return res
if __name__ == '__main__':
sol = Solution()
print(sol.findSubstring("aaaaaaaaaaaaaaaaaaaaa", ["aa","aa"]))
所用到的方法:
实现列表元素的排列组合
作者:永不止步 Python 中可以使用
例如,假设有一个列表 输出结果为:
例如,假设有一个列表 输出结果为:
|
list转str
如果列表中的元素有int型,必须先把int转成str,然后在做字符串拼接 lst = [1, 2, 3] 将所有的int转换为str lst1=list(map(lambda x:str(x),lst)) str1= ''.join(lst) 列表中的所有元素都是字符串 lst = ['a', 'b', 'c', 'd', 'e', 'f','123'] str1 = ''.join(lst) |
判断字符串是否包含子串
一、用find()方法判断要判断某一个字符串是否包含某一个子串,方法之一是可以利用python内置的字符串方法find()来查找,如果查找到,就返回子串第一个字符在原字符串中的索引位置,如果找不到,则返回-1,实例代码如下: 二、用count()方法判断count()也是python内置的字符串方法之一,可以用于统计参数指定的子串在调用对象字符串出现的次数,如果没有出现,则返回0,实例代码如下:
|
正确代码:
# encoding = utf-8
# 开发者:xxx
# 开发时间: 15:01
# "Stay hungry,stay foolish."
class Solution:
def findSubstring(self, s, words):
from collections import Counter # 用于计数可哈希对象中元素的出现次数。
# 这行代码检查输入的字符串s和单词列表words是否为空,如果其中任何一个为空,则直接返回一个空列表[]。
if not s or not words:return []
# 这行代码获取了单词列表words中的第一个单词的长度,假设所有单词长度相同。
one_word = len(words[0])
# 这行代码计算了单词列表words中所有单词的总长度。
all_len = len(words) * one_word
n = len(s)
# 这行代码使用Counter类将单词列表words转换为一个字典,其中键是单词,值是单词出现的次数。
words = Counter(words)
res = []
# 迭代范围为从0到s的长度减去all_len再加1的范围。
# 这是因为如果从i开始的子串长度小于all_len,那么就无法包含整个words中的所有单词了。
for i in range(0, n - all_len + 1):
# 这行代码获取了从索引i开始,长度为all_len的子串。
tmp = s[i:i+all_len]
# 这行代码创建了一个空列表c_tmp,用于存储从tmp中提取出的单词。
c_tmp = []
# 这行代码开始了一个循环,迭代范围为从0到all_len,步长为one_word,以提取出tmp中的每个单词。
for j in range(0, all_len, one_word):
# 这行代码将从tmp中提取出的单词添加到c_tmp列表中。
c_tmp.append(tmp[j:j+one_word])
# 这行代码检查提取出的单词列表c_tmp是否与原始单词列表words的计数相匹配。
if Counter(c_tmp) == words:
res.append(i)
return res