美文网首页
【Leetcode】30. Substring with Con

【Leetcode】30. Substring with Con

作者: 贰拾贰画生 | 来源:发表于2016-06-22 10:40 被阅读330次

对于这道题,理解题意很重要,要考虑到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 Con

      本文链接:https://www.haomeiwen.com/subject/daagdttx.html