Lua:string:评估字符是否按升序排列

时间:2016-10-18 20:37:37

标签: lua

如何评估组成字符串的所有字符是否严格按升序/降序排列?

例如:

print(is_strictly_asc_or_desc("abcdefghijklmnopqrstuvwxyz")) --> true
print(is_strictly_asc_or_desc("abba")) --> false
print(is_strictly_asc_or_desc("dj")) --> true
print(is_strictly_asc_or_desc("ace")) --> true
print(is_strictly_asc_or_desc("cent")) --> true
print(is_strictly_asc_or_desc("foot")) --> true
print(is_strictly_asc_or_desc("old")) --> true
print(is_strictly_asc_or_desc("file")) --> false
print(is_strictly_asc_or_desc("")) --> true
print(is_strictly_asc_or_desc("b")) --> true

我尝试了一些东西(但它不起作用,即使修复了,我怀疑它会有效......):

function is_strictly_asc_or_desc(s)
    local alphabet = {a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10,k=11,l=12,m=13,n=14,o=15,p=16,q=17,r=18,s=19,t=20,u=21,v=22,w=23,x=24,y=25,z=26}
    if alphabet[s[1]] < alphabet[s[2]] then
        for i,letter in ipairs(s) do
            if alphabet[s[i]] > alphabet[s[i+1]] then
                return false
            end
        end
    else
        for i,letter in ipairs(s) do
            if alphabet[s[i]] < alphabet[s[i+1]] then
                return false
            end
        end
    end
    return true
end

我们可以假设单词仅由“abcdefghijklmnopqrstuvwxyz”IE中的字符构成,只有小写字母; EG:“abc!f” - &gt;无效; “你好” - &gt;无效;等。

2 个答案:

答案 0 :(得分:2)

为了解决这个问题,我们可以遍历字符串并检查它们的字节值!

function Validate(str,asc)
    local temp = asc and 0 or math.huge
    local temp2
    for i = 1,#str do
        temp2 = str:sub(i,i):byte()
        if (ask and temp2 < temp) or temp2 < temp then
            return false
        else
            temp = temp2
        end
    end
    return true
end

编辑: 修复了接受可选升序参数的功能,这样可以确定它是否单独升序降序。我觉得这更强大,因为你可以在不同的情况下使用它。

答案 1 :(得分:1)

升序或降序的类似变化:

pom.xml