数据结构算法操作试题(C++/Python)——串联所有单词的子串
数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录
1. 题目
leetcode 链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
2. 解答
python:244ms, 11.3 MB, 70%
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if not words or not s: return []
wordLen = len(words[0])
wordsAllLen = wordLen * len(words)
words.sort()
if len(s) < wordsAllLen: return []
if len(s) == wordsAllLen and self.matchStr(s, words): return [0]
elif len(s) == wordsAllLen and not self.matchStr(s, words): return []
res = []
for i in range(0, len(s) - wordsAllLen + 1):
if s[i : i + wordLen] not in words: continue
if self.matchStr(s[i : i + wordsAllLen], words): res.append(i)
return res
def matchStr(self, string, wordsList):
lenword = len(wordsList[0])
stringList = [string[i:i+lenword] for i in range(0,len(string),lenword)]
stringList.sort()
if stringList == wordsList: return True
else:return False
其他方法看 leetcode 链接 评论区~