-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunique_chars.cc
65 lines (56 loc) · 1.9 KB
/
unique_chars.cc
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
/*
* =====================================================================================
*
* Filename: unique_chars.cc
*
* Description: Algorithm to determine if a string has all unique chars
*
* Version: 1.0
* Created: 01/26/12 00:31:30
* Revision: none
* Compiler: gcc
*
* Author: Ganesh Muniyandi (gm), [email protected]
* Company: Open Source
*
* =====================================================================================
*/
#include <iostream>
#include <string.h>
#include <bitset>
#define ASCII_SIZE 256
bool isUniqueChar1(const std::string& input) {
if (input.length() > ASCII_SIZE) return false;
bool boolean[ASCII_SIZE];
const char* pString = input.c_str();
memset(boolean, 0, ASCII_SIZE-1);
for(int i=0; i<input.size(); ++i) {
int index = static_cast<int>(*pString);
if (boolean[index]) return false;
boolean[index] = true;
++pString;
}
return true;
}
bool isUniqueChar2(const std::string& input) {
if (input.length() > ASCII_SIZE) return false;
std::bitset<ASCII_SIZE> myBits;
myBits.reset();
const char* pString = input.c_str();
for(int i=0; i<input.size(); ++i) {
int index = static_cast<int>(*pString);
if (myBits.test(index)) return false;
myBits.set(index);
++pString;
}
return true;
}
int main() {
std::string i1("UNIQE");
std::string i2("REPEATED");
std::cout << i1 << " has " << (isUniqueChar1(i1) ? "unique " : "repeated " ) << "chars." << std::endl;
std::cout << i2 << " has " << (isUniqueChar1(i2) ? "unique " : "repeated " ) << "chars." << std::endl;
std::cout << i1 << " has " << (isUniqueChar2(i1) ? "unique " : "repeated " ) << "chars." << std::endl;
std::cout << i2 << " has " << (isUniqueChar2(i2) ? "unique " : "repeated " ) << "chars." << std::endl;
return 0;
}