Leetcode030 substring-with-concatenation-of-all-words

串联所有单词的子串

题目描述:

给定一个字符串 s 和一些长度相同的单词 **words。**找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例1

输入:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

示例2

输入:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
输出:[]

解题思路:

  • 首先创建一个可以根据给定长度对字符串进行分割的函数split()函数,同时返回分割结果数组result
  • 然后根据给定words长度,因为长度都相同,因此长度 = 每个单词长度 * 单词数量(length_word * words_count)然后对s字符串进行该长度的循环和切片(self.split(s[i:i+length_word*words_count],length_word)
  • 然后需要对切片结果和words字符串进行排序和对比,如果相同则添加首字母的数组下标,不同则继续遍历

Python源码:

class Solution:
    def findSubstring(self, s: 'str', words: 'List[str]') -> 'List[int]':
        result = []
        words_count = len(words)
        if words_count>0:
            length_word = len(words[0])
        else:
            length_word = 0
        i=0 
        length_s = len(s)
        if length_s==0 or words_count==0:
            return []
        while i <= length_s-length_word*words_count:#利用while循环,实现对s遍历  
            #将s从i开始切分出一个长度和words中所有单词加在一起长度相同的一个子串,并将这个子串切开,放在string_list中                      
            string_list = self.split(s[i:i+length_word*words_count],length_word)
            #由于words中的单词并不是排好序的,所以这里需要调用两个sort函数,将这两个列表排序,这样才能够判断他们是否相等。            
            string_list.sort()
            words.sort()       
            #如果不是排好序的列表,即使里面的元素都相等,但是顺序不等的话,也是不会相等的。     
            if  string_list == words:             
                result.append(i)            
            i = i + 1        
        return result

    def split(self,string,width):
        '''
        给定长度width,把字符分隔开
        '''
        result=[]
        i=0 
        length=len(string)
        while i<=length-width:
            result.append(string[i:i+width])
            i=i+width
        return result
        

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89233998