1.1 - Is Unique
Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures

Idea:

Use bit mask to record characters.

Algorithm:

1
#include <stdio.h>
2
#include <stdbool.h>
3
4
bool isUnique(char* testStr){
5
int checker = 0;
6
7
while (*testStr != '\0'){
8
9
int bitIndex = *testStr - 'a';
10
11
if((checker & (1 << bitIndex)) > 0){
12
return false;
13
}
14
15
// update char
16
checker = checker | (1 << bitIndex);
17
testStr++;
18
}
19
return true;
20
21
}
22
Copied!

Test:

1
int main(){
2
3
char* testStr1 = "abcdertyu";
4
printf("Is the string = %s unique ? %d\n ", testStr1, isUnique(testStr1));
5
6
char* testStr2 = "abcderteu";
7
printf("Is the string = %s unique ? %d\n ", testStr2, isUnique(testStr2));
8
9
return 0;
10
}
Copied!
Copy link