Guest User

Untitled

a guest
Jan 22nd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. /*
  2. * Write a function to check if a string array has duplicate characters. you can
  3. * assume that the array will only contain characters "a-z". You can not use any
  4. * additional data structures, or modify the original string array.
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8.  
  9. /* Basic double loop: O(n^2); n = strlen(input_str) */
  10. int method1(char *input_str)
  11. {
  12. int i,j;
  13. char current_chr;
  14.  
  15. for(i=0; i<strlen(input_str); i++) {
  16. current_chr = input_str[i];
  17. for(j=i+1; j<strlen(input_str); j++) {
  18. if (input_str[j] == current_chr)
  19. return 1;
  20. }
  21. }
  22. return 0;
  23. }
  24.  
  25. /*
  26. * Use an array to store counts of repeats.
  27. * Index based on the ascii value.
  28. * Cost: O(n); n = strlen(input_str)
  29. */
  30. int method2(char *input_str)
  31. {
  32. unsigned int counters[128] = {0}; // a-z: 97-122
  33. int i;
  34.  
  35. for (i=0; i<strlen(input_str); i++) {
  36. if (counters[input_str[i]] > 0)
  37. return 1;
  38. else
  39. counters[input_str[i]]++;
  40. }
  41. return 0;
  42. }
  43.  
  44. /*
  45. * Uses just 4 bytes (int) to check for repeats
  46. * Remember ascii values: a(97) z(122)
  47. */
  48. int method3(char *input_str)
  49. {
  50. int bits = 0; // bit field
  51. int i;
  52. int pos = 0;
  53.  
  54. for (i=0; i<strlen(input_str); i++) {
  55. pos = 1 << (input_str[i] - 'a'); // Get index in the bit field (bits)
  56. if (bits & pos) // Check if was already seen
  57. return 1;
  58. else
  59. bits |= pos; // Toogle bit if not
  60. }
  61. return 0;
  62. }
  63.  
  64. /*
  65. * Same as method 3; nirav approach
  66. */
  67. int nirav_method3(char * input_str)
  68. {
  69. int result = 0;
  70. int diff;
  71. int i;
  72.  
  73. for(i=0; i<strlen(input_str); i++) {
  74. diff = input_str[i] - 'a';
  75. diff = 1 << diff;
  76. if((result & diff) != 0)
  77. return 1;
  78. result = result | diff;
  79. }
  80. return 0;
  81. }
  82.  
  83. int main(int argc, char *argv[]) // FIXME: Check input
  84. {
  85. char *input_str = argv[1]; // FIXME: check is not NULL
  86.  
  87. printf("%s: %d\n", input_str, method1(input_str));
  88. printf("%s: %d\n", input_str, method2(input_str));
  89. printf("%s: %d\n", input_str, method3(input_str));
  90. printf("%s: %d\n", input_str, nirav_method3(input_str));
  91. return 0;
  92. }
Add Comment
Please, Sign In to add comment