数据结构算法操作试题(C++/Python)——串联所有单词的子串

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(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 链接 评论区~