Create an algorithm that checks whether two strings have the same characters (duplicates don't matter). Assuming a char == 1 byte so there are 2^8 = 256 possible characters.
Function prototype given: int HasSameChars(char *c1, char *c2);
------------------------------
The algorithm that I've come up with is:
The following in C code is this...Code:- array a[256], b[256] - for char in c1: a[char] = 'y'; // meaning we flag with 'y' that it exists - for char in c2: b[char] = 'y'; - for i = 0 to 256: if a[i] != b[i] return false; - return true;
PHP Code:
#include <stdio.h>
#include <string.h>
#define MAX_NUM_CHARS 256
#define TRUE 1
#define FALSE 0
int HasSameChars(char *c1, char *c2)
{
char tbl[2][MAX_NUM_CHARS];
int i = 0;
if (c1 == NULL || c2 == NULL)
{
printf("invalid input\n");
return FALSE;
}
memset(tbl, 0, 2 * MAX_NUM_CHARS);
for (i = 0; i < strlen(c1); i++)
{
tbl[0][*(c1+i)] = 'm';
}
for (i = 0; i < strlen(c2); i++)
{
tbl[1][*(c2+i)] = 'm';
}
for (i = 0; i < MAX_NUM_CHARS; i++)
{
if (tbl[0][i] != tbl[1][i])
{
return FALSE;
}
}
return TRUE;
}
int main()
{
char str1[] = "aflkj4 lkj34l fkj alkdjf flkaj wecae4cp9cj alkdjgfdsf";
char str2[] = "aflkj4 lkj34l fkj alkdjf flkaj wecae4cp9cj alkdjgfdsf";
if (HasSameChars(str1, str2))
{
printf("has same chars\n");
} else {
printf("does not have same chars\n");
}
return 0;
}
Is this the optimal solution? I have a feeling it's not the optimal solution in terms of space, but it seems speedy...
Code:bash-4.0$ time cmpr has same chars real 0m0.003s user 0m0.001s sys 0m0.002s