Lua:string:判断字符是否按照升序排列

如何判断一个字符串的所有字符是否都按照严格的升序/降序排列?

例如:

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”中的字符构成,即仅包含小写字母;例如:“abc!f”-->无效;“Hello”-->无效;等等。

原文链接 https://stackoverflow.com/questions/40117638

点赞
stackoverflow用户3979429
stackoverflow用户3979429

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

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 (asc and temp2 < temp) or temp2 < temp then
            return false
        else
            temp = temp2
        end
    end
    return true
end

编辑: 修正函数以接受可选的升序参数,这允许您单独确定升序或降序。我认为这更加强大,因为您可以在不同情况下使用它。

2016-10-18 20:55:26
stackoverflow用户3735873
stackoverflow用户3735873
## 一个相似的函数,用于判断字符串是否严格升序或降序:

function is_strictly_asc_or_desc(s) while #s > 2 and s:sub(2,2) == s:sub(1,1) do s = s:sub(2) end # 删除前缀相同的字符 local temp = s:sub(1,1) local up = s:sub(2,2) > temp # 标记升序还是降序 for c = 2, #s do c = s:sub(c,c) if up and c < temp or not up and c > temp then return false end # 如果不是按照升序或降序排列,返回false temp = c end return true end

```

2016-10-18 22:51:44