简体   繁体   English

实现O(n)算法以确定字符串是否具有所有唯一字符?

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

Here I have O(n^2) algorithm implemented in C++ function to determine if a string have all unique characters. 这里我在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;
}

This algorithm checks every char of the string with other char of the string in order to find if they are repeated. 此算法使用字符串的其他字符检查字符串的每个字符,以查找它们是否重复。 This approach have time complexity of O(n^2) with no space complexity. 该方法具有O(n ^ 2)的时间复杂度,没有空间复杂性。 Can someone suggest an algorithm implementation of time complexity O(n) ? 有人可以建议时间复杂度O(n)的算法实现吗?

You could keep an unordered_set<char> of characters that you've already seen, and bail out if the character you're at is already in the set. 你可以保留一个你已经看过的unordered_set<char>字符,如果你所在的角色已经在集合中,就会纾困。 Because access to the set is amortized constant time, your algorithm will run in O(n). 由于对集合的访问是按照常量时间分摊的,因此您的算法将在O(n)中运行。

Instead of a set, you could also use an array of bool , because a char typically has a very small range (0-255). 您也可以使用bool数组代替集合,因为char通常具有非常小的范围(0-255)。

The following has a time complexity of O(N) : 以下时间复杂度为O(N)
It counts each character and stop once character is not unique. 它会对每个角色进行计数,并在角色不唯一时停止。

bool IsUnique(const char *str)
{
    char counts[256] = {0};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM