如何优化此 Lua 函数?

目前只是想要让这个代码运行更快。

此函数当前接受一个字符串 s 和一个整数 k,并返回 s 长度为 k、元音字母最多的子字符串。

例如:

s = caberqiitefg
k = 5

输出:

erqii

erqii 是在字符串 s 中长度为 5、元音字母最多的子字符串。

如果在字符串中没有元音字母,则返回 “Not found!”。

function findSubstring(s, k)
    local sub = string.sub
    local gsub = string.gsub
    local vowels = "[aeiou]"
    local empty = ""
    local _, numberOfVowels = gsub(s, vowels, empty)
    if numberOfVowels == 0 then
        return "Not found!"
    end
    local mostVowels = nil
    local vowelnum = 0
    for i = 1, #s - k + 1 do
        local curr = sub(s, i, k + i - 1)
        local _, nvow = gsub(curr, vowels, empty)
        if mostVowels == nil or (nvow > vowelnum) then
            mostVowels = curr
            vowelnum = nvow
        end
    end
    return mostVowels
end
点赞
用户4984564
用户4984564

不完全是这样,但我发现在某些情况下这个修改版本运行得更好

function findSubstring2(s, k)
    local sub = string.sub
    local gsub = string.gsub
    local vowels = "[aeiou]"
    local empty = ""
    local _, numberOfVowels = gsub(s, vowels, empty)
    if numberOfVowels == 0 then
        return "Not found!"
    end

    local candidate = nil
    local vowelnum = 0
    local i=1
    while i <= #s-k+1 do
        local curr = sub(s, i, k + i - 1)
        local _, nvow = gsub(curr, vowels, empty)
        if nvow > vowelnum then
            candidate = curr
            vowelnum = nvow
        end
        i=i+(curr:find(vowels) or #curr)
    end
    return candidate
end

正如您所看到的,它总是跳到下一个元音字母,这样做有利于 在一长串辅音字母之前寻找高k的长s 中提高速度。同时,这也意味着如果第一个元音字母出现在“#s-k”的后面(子字符串可能开始的最后一个位置),它可能会跳过一个有效的序列,这需要通过一些特殊情况进行处理。

这种加速是否值得取决于您的平均输入字符串的呈现方式。

2020-05-27 10:36:57
用户15074170
用户15074170
str1 = 'caberqiitefg'
k = 5
j = k
max = 0
max_sub = ""
arr = ["a","e","i","o","u"]
for i in range(len(str1)):
    sub = str1[i:j]
    p= 0
    for m in arr:
        p += sub.count(m)
    if p!= 0 and p>max:
        max = p
        max_sub = sub
    j+=1
print(max_sub)

我使用了少量变量和一个列表来降低空间复杂度。

2021-01-25 04:16:43