#include <string>
using namespace Std;
BOOL IsUniqueChars2 (String str)
{
if (Str.length () >) return false;
BOOL *char_set = new bool[256];
memset (char_set, 0, sizeof (BOOL) * 256);
for (int i = 0; i < str.length (); i++)
{
int val = str[i];
if (Char_set[val])//This character has already appeared in the string
{
return false;
}
Char_set[val] = true;
}
return true;
}
The time complexity of this code is O (n), where n is the length of the string and the space complexity is O (1).
using bit vectors , you can reduce the footprint to the original 1/8. The following code assumes that the string contains only lowercase letters A through Z. In this way, we only need to use an int type variable.
#include <string>
using namespace Std;
BOOL Isuniquechars (String str)
{
if (Str.length >) return false;
int checker = 0;
for (int i = 0; i < str.length (); i++)
{
int val = str[i]-' a ';
if ((checker& (1 << val)) > 0)
{
return false;
}
Checker |= (1 << val);
}
return true;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Array and string to determine if each character of the string is different