给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明:
字母异位词指字母相同,但排列不同的字符串。
不考虑答案输出的顺序。
示例 1:
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
local MAX_LENTH = 20100
local function func_438(s, p)
-- body
local left, right, retIndex = 1, 1, {}
local win, needs = {}, {}
local match, needs_size = 0, 0
-- 规则装填dict
for i=1, #p do
local c = string.byte(p, i)
if needs[c] == nil then needs_size = needs_size + 1 end
needs[c] = needs[c] == nil and 1 or needs[c] + 1
end
while right <= #s do
local c1 = string.byte(s, right)
if needs[c1] ~= nil then
win[c1] = win[c1] == nil and 1 or win[c1] + 1
if win[c1] == needs[c1] then
match = match + 1
end
end
right = right + 1
while match == needs_size do
if right - left == #p then
retIndex[#retIndex+1] = left
end
local c2 = string.byte(s, left)
if needs[c2] ~= nil then
win[c2] = win[c2] - 1
if win[c2] < needs[c2] then
match = match - 1
end
end
left = left + 1
end
end
return retIndex
end
local s = "cbaebabacd"
local p = "abc"
for i,v in ipairs(func_438(s, p)) do
print(i,v)
end
结果:
1 1
2 7