30. Substring with Concatenation of All Words
Problem 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:1
2
3
4
5
6Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:1
2
3
4Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []
Solution:
Use two hash table.
- First hash table,
map
, stores every words. - Second hash table,
seen
, determine if a substring is in themap
or not. If the substring is not in the map, it means the substring is not a word in given words. In addition, it can only appear once in current search, so if the count inseen
is greater than in themap
, we should break the loop.
1 | class Solution { |
time complexity: $O(n*num)$
space complexity: $O(words.size())$
reference:
https://goo.gl/wy6wAq
https://goo.gl/MAkUfJ