Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //============================================================================
- // Name : UniqueCharString.cpp
- // Author : Kevin Parks
- // Version : 1.0
- // Copyright : MIT License
- // Description : Determines if a string contains all unique characters (ASCII)
- //============================================================================
- #include <iostream>
- #include <vector>
- #define TABLELEN (128)
- /**
- * \brief isUniqueCharString determines if a string has all unique characters
- * \param str const reference to the std::string to check
- * \return true if all chars are unique, false otherwise
- */
- bool isUniqueCharString(const std::string &str)
- {
- // First check if string is longer than ASCII chars, must have repeat if so
- // ASCII has 128 chars possible if you count everything
- if(str.length() >= TABLELEN)
- return false;
- // "hash" each character index. If the index has a 1 value, it's not unique
- int charTable[TABLELEN] = { 0 };
- for(unsigned i = 0; i < str.length(); ++i)
- {
- int curChar = (int)str[i];
- if(charTable[curChar] == 1)
- {
- // Value has been found before
- return false;
- }
- else
- {
- charTable[curChar] = 1;
- }
- }
- // Never found non-unique value
- return true;
- }
- int main() {
- std::cout << "UniqueCharString" << std::endl;
- std::vector<std::string> strings;
- strings.push_back("test");
- strings.push_back("abcd");
- strings.push_back("`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./");
- for(unsigned i = 0; i < strings.size(); ++i)
- {
- if(isUniqueCharString(strings[i]))
- {
- std::cout << strings[i] << " has all unique characters" << std::endl;
- }
- else
- {
- std::cout << strings[i] << " does not have all unique characters" << std::endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement