-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp2.cpp
More file actions
49 lines (40 loc) · 1.24 KB
/
p2.cpp
File metadata and controls
49 lines (40 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Problem:
// Implement an algorithm to determine if a string has all unique characters.
// what if you cannot use additional data structures?
// E.g.: "Algorithm" return true while "Common" returns false
// BCR = O(n)..you need to visit all the chars at least once
// BF solution ( O(n^2) = 1 + 2 + 3 ... + n = n ( n + 1 ) / 2 ):
// Start with dropping pin on 1st char & move along the array and break if
// same char found. Move ping to next char do the same operation
// Better solution ( O(n) ) :
// Create 128 bit associative array of bools and drop the pin on 1st char
// and check if value on bool array corresponding to the dropped pin is
// set to the true then return true
#include <iostream>
#include <string>
#include <vector>
bool isUnique(std::string str)
{
bool bitmap[26] = {false};
unsigned int i = 0;
for( auto c : str ) {
//Convert if problem assumes 'A' == 'a'
if( c < 'a' ) {
unsigned int distance = c - 'A';
i = 'a' + distance;
} else {
i = c - 'a';
}
if( bitmap[i] ) {
return false;
} else {
bitmap[i] = true;
}
}
return true;
}
int main(int argc, char **argv)
{
std::cout << "isUnique(\"Algoritham\") = " << isUnique("Algoritham") << std::endl;
return 0;
}