【Leetcode】30. Substring with Concatenation of All Words

【Leetcode】30. Substring with Concatenation of All Words_第1张图片

对于这道题,理解题意很重要,要考虑到words中出现重复单词的情况。并且,要求找出所有的可能的index(包括重叠可能),举个例子,如果 s='abcdefcd'words=['cd', 'ef'],那么应返回 [2, 4]
用了好几种方案,都不能解决问题。最后的解题思路是:假设word长度为 length,个数是 n,从索引 x=0开始,如果 s[x:x+length]是words中一员,那么从 x开始从s中截取所有words拼接长度的字符串 ss=s[x:x+length*n],在函数 isValid中判断该子串是否是所有 words的拼接,如果是则记录索引。在 isValid中的判断思路是,根据 word长度,将 ss划分成list列表 words_ss,然后遍历 words,每遍历一个 word,判断 words_ss中有无此 word,若无,直接返回 False;若有,则从 word_ss中删除该 word。遍历结束,返回 True

class Solution(object):
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        if len(words) == 0:
            return []
        length = len(words[0])
        if length > len(s):
            return []
        count_c = len(words) * length
        res = []
        i = 0
        while i < len(s) - count_c + 1:
            word = s[i:i + length]
            if word in words:
                ss = s[i:i + count_c]
                if self.isValid(ss, words, length):
                    res.append(i)
                i += 1
            else:
                i += 1
        return res

    def isValid(self, ss, words, length):
        words_ss = []
        for x in xrange(len(ss) / length):
            word = ss[x * length:(x + 1) * length]
            words_ss.append(word)
        for word in words:
            if word in words_ss:
                words_ss.remove(word)
            else:
                return False
        return True

你可能感兴趣的:(【Leetcode】30. Substring with Concatenation of All Words)