1.1. Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
我想到的是位图法。但是位图法有一个缺点,如果用int的话,也只能表示32的字符。看着答案是用的256的那个哈希,这难道不是额外的空间吗?不过后面答案给了第二个方案是用的位图法。给出C++代码
bool isUniqueChars(char * chr)
{
bool char_set[256] = {false};
while (*chr != '\0')
{
int value = *chr;
if (char_set[value] == true)
return false;
else
char_set[value] = true;
}
return true;
}
bool isUniqueChars2(char * chr)
{
int checker = 0;
while(*chr !=='\0')
{
int value = *chr - 'A';
if (checker & (1<<value) > 0)
return false;
else
checker |= (1<<value);
}
return true;
}