Substring with Concatenation of All Words

来源:互联网 发布:设计师素材网站知乎 编辑:程序博客网 时间:2024/06/14 07:29

题目描述:

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) ins that is a concatenation of each word inwords 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中得到相应的index、不出意外超时了。


后来用hashtable,创建map<string,integer>,int记录单词的个数,这样也超时了。此时的复杂度是O(m*n):


后来参考了别人的做法,实在是巧妙。


0 0
原创粉丝点击