30. Substring with Concatenation of All Words

题目

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]

You should return the indices: [0,9].
(order does not matter).

分析

解决该问题的关键是理解清楚要求。
给定一个目标字符串s,一个单词集合words。
要求使得words集合中所有元素连续出现在s中的首位置组成的集合(元素顺序不考虑)。

正如所给实例,目标字符串s: “barfoothefoobarman”
对比单词集合words: [“foo”, “bar”]
我们发现,在pos=0 ~ 5时“barfoo”恰好匹配,则0加入结果result;
在pos=9 ~ 14时“foobar”恰好匹配,则9加入结果result;

在理清楚题意后,便可入手程序实现。

class Solution(object):
    ##判断是否有words中的单组组成
    def isEqual(self, s, words, n):
        sList = []
        i = 0
        // 将字符串按照 words中每个单词的长度截取成数组
        while(i<len(s)):
            sList.append(s[i:i+n])
            i = i + n
        sList.sort()
        words.sort()
        if sList== words:
            return True
        else:
            return False
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        if len(words)<=0:
            return
        n = len(words[0])
        lenWord = n *len(words)
        result = []
        i = 0
        #注意while 的跳出条件 只需要循环 len(s)-lenWord次就够了
        while(i<=len(s)-lenWord):
            sCurrent = s[i:i+n]
            if sCurrent in words:
                #取出长度等于words中所有单词组成字符串的长度的S的字串
                sSub = s[i:lenWord+i]
                if self.isEqual(sSub, words,n):
                    result.append(i)
            #每次i增1     
            i += 1
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值