leetcode面试题 判断字符是否唯一

⭐️ 题目描述

leetcode面试题 判断字符是否唯一_第1张图片


leetcode链接:判断字符是否唯一

思路: 'a' - 'z'ASCII 区间在 [97 , 122] 当中的每个减去 97 或者 'a' 都会变成 0 - 25,所以只需要一个数组,用当前元素减去 97 97 97 的下标来记录当前字母出现的次数即可。

1️⃣ 代码:

bool isUnique(char* astr){
    char hash[26] = {0};
    int i = 0;
    while (astr[i]) {
        // 防止 char 溢出
        if (hash[astr[i] - 97] < 128) {
            hash[astr[i] - 97]++;
        }
        i++;
    }

    for (int i = 0; i < 26; i++) {
        if ((hash[i] != 1) && (hash[i] != 0)) {
            return false;
        }
    }

    return true;
}

你可能感兴趣的:(刷题,leetcode,学习,刷题)