我想获得字符串中最常见的 k 大小子字符串。为此,我使用一个表来存储每个子字符串的出现次数。这是代码:
function frequentWords(seq, k)
local subs = ""
local counter = {}
for i = 1,(seq:len()-k+1) do
subs = seq:sub(i, i+k-1)
counter[subs] = (counter[subs] and counter[subs] + 1 or 1)
--print(subs .. ": " .. counter[subs])
end
end
这条线counter[subs] = (counter[subs] and counter[subs] + 1 or 1)
的均值相同 counter[subs] = (counter[subs] ? counter[subs]+1 : 1)
。这条线只有counter[subs] = counter[subs] + 1
当我们可以counter
用0
. 这在Lua中可能吗?如果没有,做类似事情的最佳方法是什么?
例如,在 Ruby 中,这是通过像这样声明一个 Hash 来完成的:
counter = Hash.new(0)