You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
下面代码是自己写的,思路也是设定移动的窗口,虽然能过,但是效率很低,runtime是1500ms左右~
class Solution:
# @param S, a string
# @param L, a list of string
# @return a list of integer
def findSubstring(self, S, L):
if S is None or len(S) == 0 or L is None or len(L) == 0: return []
wordLen = len(L[0])
start = 0; res = []
while start <= len(S) - wordLen * len(L):
map = []; pre = start; last = start + wordLen
while last <= len(S) and len(map) < len(L) and S[pre: last] in L:
map.append(S[pre: last])
pre = last; last += wordLen
if sorted(map) == sorted(L):
res.append(start)
start += 1
return res
然后参考了别人优化过的解法~runtime降到了90ms左右~但是思路要稍微复杂一点,不是很好理解~这种解法时间复杂度为O(N)~
思路仍然是维护一个窗口,如果当前单词在字典中,则继续移动窗口右端,否则窗口左端可以跳到字符串下一个单词了。假设源字符串的长度为n,字典中单词的长度为l。因为不是一个字符,所以我们需要对源字符串所有长度为l的子串进行判断。做法是i从0到l-1个字符开始,得到开始index分别为i, i+l, i+2*l, ...的长度为l的单词
(From http://blog.csdn.net/linhuanmars/article/details/20342851)
class Solution:
# @param S, a string
# @param L, a list of string
# @return a list of integer
def findSubstring(self, S, L):
if S is None or len(S) == 0 or L is None or len(L) == 0: return []
wordLen = len(L[0])
start = 0; res = []
dict = collections.defaultdict(int)
for word in L: dict[word] += 1
for i in xrange(wordLen):
left, count = i, 0
newDict = collections.defaultdict(int)
for j in xrange(i, len(S) - wordLen + 1, wordLen):
str = S[j: j + wordLen]
if str in dict:
newDict[str] += 1
if newDict[str] <= dict[str]:
count += 1
else:
while newDict[str] > dict[str]:
str1 = S[left : left + wordLen]
newDict[str1] -= 1
if newDict[str1] < dict[str1]: count -= 1
left += wordLen
if count == len(L):
res.append(left)
newDict[S[left: left + wordLen]] -= 1
count -= 1
left += wordLen
else:
newDict.clear()
count = 0
left = j + wordLen
return res