1. 程式人生 > >2017-7-21未命名文件

2017-7-21未命名文件

auto ace orm ott ont ise borde ria rgb

2017-7-21未命名文件

新建模板小書匠

第一章 Arrays And Strings

  • 1.1 Is_unique.cpp
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4. #include <bitset>
  5. using namespace std;

  6. bool isUniqueChars(const string &str)
  7. {
  8. if (str.length() > 128)
  9. {
  10. return false;
  11. }
  12. vector<bool> char_set(128
    );
  13. for (int i = 0; i < str.length(); i++)
  14. {
  15. int val = str[i];
  16. if (char_set[val])
  17. {
  18. return false;
  19. }
  20. char_set[val] = true;
  21. }
  22. return true;
  23. }

  24. bool isUniqueChars_bitvector(const string &str) {
  25. //Reduce space usage by a factor of 8 using bitvector.
  26. //Each boolean otherwise occupies a size of 8 bits.

  27. bitset<256> bits(0);
  28. for(int i = 0; i < str.length(); i++) {
  29. int val = str[i];
  30. if(bits.test(val) > 0) {
  31. return false;
  32. }
  33. bits.set(val);
  34. }
  35. return true;
  36. }
  37. bool isUniqueChars_noDS(const string &str) {
  38. for(int i = 0; i < str.length()-1; i++) {
  39. for(int j = i+1; j < str.length(); j++) {
  40. if(str[i] == str[j]) {
  41. return false;
  42. }
  43. }
  44. }
  45. return true;
  46. }

  47. int main(){
  48. vector<string> words = {"abcde", "hello", "apple", "kite", "padle"};
  49. for (auto word : words)
  50. {
  51. cout << word << string(": ") << boolalpha << isUniqueChars(word) <<endl;
  52. }
  53. cout <<endl << "Using bit vector" <<endl;
  54. for (auto word : words)
  55. {
  56. cout << word << string(": ") << boolalpha << isUniqueChars_bitvector(word) <<endl;
  57. }
  58. cout <<endl << "Using no Data Structures" <<endl;
  59. for (auto word : words)
  60. {
  61. cout << word << string(": ") << boolalpha << isUniqueChars_bitvector(word) <<endl;
  62. }
  63. return 0;
  64. }

2017-7-21未命名文件