leetcode_30. 串联所有单词的子串

leetcode_30. 串联所有单词的子串

题目

leetcode题目链接

思路分析1

题目要求:找出 由words数组组成的字符串(每一个元素word等长),在字符转s中的位置

  1. 数组words生成的字典dic2
  2. 遍历字符串,从头开始判断长度为lenwords的字符串 生成的字典dic1
  3. 如果dic1 与 dic2 相同,说明找到

代码展示1

    def findSubstring(self, s: str, words):
        if s =="" or words ==[]:
            return[]
        res =[]
        lenwords = len(words[0]*len(words))
        #数组words生成的字典dic2
        dic2 = self.help2(words)
        for i in range(len(s)-lenwords+1):
            #从头开始判断长度为lenwords的字符串 生成的字典dic1
            dic1 = self.help1(s[i:i+lenwords],len(words[0]))
            if dic1==dic2:
                res.append(i)
        return res
    #通过 字符串str 和每一个单词的长度interval,生成字典
    def help1(self,str,interval):
        dic = {}
        for i in range(0,len(str)-interval+1,interval):
            if str[i:i+interval] not in dic:
                dic[str[i:i+interval]] = 1
            else:
                dic[str[i:i+interval]] += 1
        return dic
    #通过数组words 生成字典
    def help2(self,words):
        dic ={}
        for i in words:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1
        return dic

思路分析2

题目要求:找出 由words数组组成的字符串(每一个元素word等长),在字符转s中的位置

  1. 对数组words排序
  2. 遍历字符串,对长度为totallen的字符串,拆成数组,排序
  3. 如果 排好序的数组 相同,说明找到

代码展示2

    def findSubstring2(self, s: str, words):
        if s =="" or words ==[]:
            return[]
        res =[]
        #对单词数组进行排序
        words = sorted(words)
        totallen = len(words[0])*len(words)
        wordlen = len(words[0])
        for i in range(len(s)-totallen+1):
            temp = []
            #对长度为totallen的字符串,拆成数组
            for j in range(0,totallen,wordlen):
                temp.append(s[i+j:i+j+wordlen])
            temp = sorted(temp)
            if temp == words:
                res.append(i)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值