-
Notifications
You must be signed in to change notification settings - Fork 510
/
Copy path1. Is_unique.cpp
85 lines (75 loc) · 1.82 KB
/
1. Is_unique.cpp
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <string>
#include <vector>
#include <iostream>
#include <bitset>
#include <map>
#include <algorithm> // for sort()
using namespace std;
bool isUniqueChars(const string &str){
if (str.length() > 128){
return false;
}
vector<bool> char_set(128);
for (int i = 0; i < str.length(); i++){
int val = str[i];
if (char_set[val]){
return false;
}
char_set[val] = true;
}
return true;
}
bool isUniqueChars_bitvector(const string &str) {
//Reduce space usage by a factor of 8 using bitvector.
//Each boolean otherwise occupies a size of 8 bits.
bitset<256> bits(0);
for(int i = 0; i < str.length(); i++) {
int val = str[i];
if(bits.test(val) > 0) {
return false;
}
bits.set(val);
}
return true;
}
bool isUniqueChars_noDS( string str) {
sort(str.begin(), str.end()); // O(nlogn) sort from <algorithm>
bool noRepeat = true;
for ( int i = 0 ; i < str.size() - 1; i++){
if ( str[i] == str[i+1] ){
noRepeat = false;
break;
}
}
return noRepeat;
}
bool is_unique(string str){
map<char, int> character_counts;
for (char c: str){
for (auto it=character_counts.begin(); it!=character_counts.end(); it++){
if (c==it->first){
return false;
}
}
character_counts[c]=1;
}
return true;
}
int main(){
vector<string> words = {"abcde", "hello", "apple", "kite", "padle"};
for (auto word : words)
{
cout << word << string(": ") << boolalpha << isUniqueChars(word) <<endl;
}
cout <<endl << "Using bit vector" <<endl;
for (auto word : words)
{
cout << word << string(": ") << boolalpha << isUniqueChars_bitvector(word) <<endl;
}
cout <<endl << "Using no Data Structures" <<endl;
for (auto word : words)
{
cout << word << string(": ") << boolalpha << isUniqueChars_noDS(word) <<endl;
}
return 0;
}