Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. //============================================================================
  2. // Name : UniqueCharString.cpp
  3. // Author : Kevin Parks
  4. // Version : 1.0
  5. // Copyright : MIT License
  6. // Description : Determines if a string contains all unique characters (ASCII)
  7. //============================================================================
  8.  
  9. #include <iostream>
  10. #include <vector>
  11.  
  12. #define TABLELEN (128)
  13.  
  14. /**
  15. * \brief isUniqueCharString determines if a string has all unique characters
  16. * \param str const reference to the std::string to check
  17. * \return true if all chars are unique, false otherwise
  18. */
  19. bool isUniqueCharString(const std::string &str)
  20. {
  21. // First check if string is longer than ASCII chars, must have repeat if so
  22. // ASCII has 128 chars possible if you count everything
  23. if(str.length() >= TABLELEN)
  24. return false;
  25.  
  26. // "hash" each character index. If the index has a 1 value, it's not unique
  27. int charTable[TABLELEN] = { 0 };
  28. for(unsigned i = 0; i < str.length(); ++i)
  29. {
  30. int curChar = (int)str[i];
  31. if(charTable[curChar] == 1)
  32. {
  33. // Value has been found before
  34. return false;
  35. }
  36. else
  37. {
  38. charTable[curChar] = 1;
  39. }
  40. }
  41.  
  42. // Never found non-unique value
  43. return true;
  44. }
  45.  
  46. int main() {
  47. std::cout << "UniqueCharString" << std::endl;
  48. std::vector<std::string> strings;
  49. strings.push_back("test");
  50. strings.push_back("abcd");
  51. strings.push_back("`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./");
  52. for(unsigned i = 0; i < strings.size(); ++i)
  53. {
  54. if(isUniqueCharString(strings[i]))
  55. {
  56. std::cout << strings[i] << " has all unique characters" << std::endl;
  57. }
  58. else
  59. {
  60. std::cout << strings[i] << " does not have all unique characters" << std::endl;
  61. }
  62. }
  63.  
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement