实现O(n)算法来确定字符串是否所有字符都是唯一的
Implement O(n) algorithm for determining if a string has 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;
}
该算法将字符串的每个字符与字符串的其他字符进行检查,以查找它们是否重复。该方法的时间复杂度为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;
}
相关文章:
- 检查向量是否具有所有可能的字符组合
- 我是否不正确地集中了这些字符数组?
- 是否可以在 c++ 中将两位数保存在无符号字符中
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- "std::string"是否将其字符作为签名字符在内部存储?
- 是否有任何区域设置会影响宽字符编码?
- 如何检查用户是否输入了元音字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 对于多个字符(如 ETX/STX 对),是否有类似于 std::quote 的东西
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何检查二维字符数组是否有空字
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 常量字符*是否有任何例外?
- 拆分字符串输入并查找字符是否有效
- CPP 中的 ++ 运算符对字符是否有任何重载?
- 是否可以转换预处理器指令中的字符?