Description:
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.
Example 1:
Input: s = “barfoothefoobarman”, words = [“foo”,”bar”] Output: [0,9]
Example 2:
Input: s = “wordgoodstudentgoodword”, words = [“word”,”student”] Output: []
解法:
题意有点绕,意思是是给你一个字符串,和一个字符串的数组,需要返回一个该字符串的索引组成的数组,其中字符串数组中各成员长度要求一致,返回的索引有如下性质:
从每个索引开始,长度为L的字串需要精确包含字符串数组中的所有字符串(不多不少)。L 为字符串数组中所有字符串长度之和。
思路是:先用一个Map结构,记录字符串数组中各个字符串出现的个数,用于之后判断子串中各字符串是否出现够数,之后,从头开始遍历字符串,找和字符串数组中的字符串相同的字串,找到后map中的值减一,否则重新初始化map,从下一个字符开始遍历。如果map中所有的值都为0,则找到了一个符合条件的子串,索引压入数组。
代码如下:
1 | class Solution { |