实现O(n)算法来确定字符串是否所有字符都是唯一的

Implement O(n) algorithm for determining if a string has all unique characters?

本文关键字:是否 字符 唯一 字符串 算法 实现      更新时间:2023-10-16

这里我有一个在c++函数中实现的O(n^2)算法来确定字符串是否所有字符都是唯一的

bool IsUnique2(char *str)
{
    char instr[256];
    strcpy(instr,str);
    bool repeat = false;
    int i;
    for(i = 0; i<strlen(instr); i++)
    {
        int j;
        for(j=i+1; j<strlen(instr); j++)
        {
            if(instr[i]==instr[j])
            {repeat = true; break;}
        }
        if(repeat) break;
    }
    return !repeat;
}

该算法将字符串的每个字符与字符串的其他字符进行检查,以查找它们是否重复。该方法的时间复杂度为0 (n^2),没有空间复杂度。谁能建议一个时间复杂度为O(n)的算法实现?

你可以保留你已经看到的字符的unordered_set<char>,如果你看到的字符已经在集合中,则退出。因为对集合的访问是常数时间平摊的,所以你的算法将在O(n)内运行。

您也可以使用bool数组而不是集合,因为char通常具有非常小的范围(0-255)。

以下具有O(N)的时间复杂度:
它计算每个字符,一旦字符不唯一就停止。

bool IsUnique(const char *str)
{
    char counts[256] = {0};
    for (; *str != ''; ++str) {
        const unsigned char c = *str;
        ++counts[c];
        if (counts[c] > 1) {
             return false;
        }
    }
    return true;
}