【每日一题1031】连续字母

:woman_mage: 给定一个只包含小写英文字母的字符串words,请编写一个函数,判断它是否它其中的字母是否是连续的。每个字母最多只能出现一次,并且顺序不影响。

示例:
输入:dabc,输出:True
输入:dab,输出:False

题目难度:简单
题目来源:codewars: Consecutive letters

def is_ consecutive(words: str) -> bool:
    pass

assert is_ consecutive("abc") is True
assert is_ consecutive("dab") is False
assert is_ consecutive("dabc") is True
assert is_ consecutive("v") is True
def is_consecutive(words: str) -> bool:
    index_words = words + words[0]
    num = 0
    for i in range(len(words)):
        if ord(index_words[i + 1]) - ord(index_words[i]) != 1:
            num += 1
            if num >= 2:
                return False
    return True
assert is_consecutive("bca") is True

这样会报错哦

是的,想复杂了

def is_consecutive(words: str) -> bool:
    ord_list = [ord(w) for w in words]
    ord_list.sort()
    for i in range(1, len(ord_list)):
        if ord_list[i] - ord_list[i-1] != 1:
            return False
    return True


assert is_consecutive("abc") is True
assert is_consecutive("dab") is False
assert is_consecutive("dabc") is True
assert is_consecutive("v") is True
def is_consecutive(words: str) -> bool:
    wordL = list(words)
    wordL.sort()
    return  [False for i in range(len(wordL)-1) if ord(wordL[i]) != ord(wordL[i+1]) -1 ] == []

assert is_consecutive("abc") is True
assert is_consecutive("dab") is False
assert is_consecutive("dabc") is True
assert is_consecutive("v") is True
public boolean consecutive(String str) {
        char[] chars = str.toCharArray();
        ArrayList<Character> chars1 = new ArrayList<>();
        for (int i = 0; i < chars.length; i++) {
            chars1.add(chars[i]);
        }
        List<Character> collect = chars1.stream().sorted().collect(Collectors.toList());
        int i = 0;
        while (i < collect.size()-1) {
            if (Integer.valueOf(collect.get(i)).equals(Integer.valueOf(collect.get(i + 1))-1)) {
                i++;
            } else {
                return false;
            }
        }
        return true;
    }
def is_consecutive(words: str) -> bool:
    ord_list = [ord(i) for i in words]
    ord_list.sort()
    print(ord_list)
    for j in range(1, len(ord_list)):
        if ord_list[j - 1] + 1 != ord_list[j]:
            return False
    return True


assert is_consecutive("abc") is True
assert is_consecutive("dab") is False
assert is_consecutive("dabc") is True
assert is_consecutive("v") is True
关闭