Thursday, March 3, 2011

Check if duplicate characters present in string

The problem we are discussing here is you have to return true if string specified contain at least one duplicate character. First we will be trying this without using the additional buffer. 


Idea is just simple: Try comparing each character from second character to end, with every character from start to that character. Don't try to compare from first character, otherwise  you will find the first match at the start itself.




bool IsDuplicatesCharPresent(char* pchStringToVerify)
{
if(pchStringToVerify == NULL)
return false;


char *pchStringStart = pchStringToVerify++;


while(pchStringToVerify != NULL)
{
char* pchComparator = pchStringStart;
while(pchComparator != pchStringToVerify)
{
if(*pchComparator == *pchStringToVerify)
{
return true;
}
pchComparator++;
}
pchStringToVerify++;
}
return false;
}




This can also be done using additional buffer, but your additional buffer may vary using as per the string character set. For example suppose if you are sure of having only ASCII characters then you will require buffer of size 256 length only, as shown below.



bool IsDuplicatesCharPresent(char* pchStringToVerify)
{
if(pchStringToVerify == NULL || (pchStringToVerify + 1) == NULL)
return false;
bool bArray[256] = {false};


while(*pchStringToVerify != NULL)
{
if(true == bArray[ (int)*pchStringToVerify ] )
return true;
else
bArray[ (int)*pchStringToVerify ] = true;
pchStringToVerify++;
}


return false;
}


This code is written considering the string is C style string, i.e. terminating with NULL. 

No comments:

Post a Comment