1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
字符串问题,需要先确定是不是只有ASCII码。
如果是,可以用char[256],也可以用位向量。位向量的实现参照《编程珠玑》。i&MASK就是取余。i>>SHIFT就是取商。
1 class BitVector { 2 public: 3 BitVector(int n) { 4 arr = new int[1 + n / INT_LEN]; 5 memset(arr, 0, (1 + n / INT_LEN) * sizeof(int)); 6 } 7 8 ~BitVector() {delete[] arr;} 9 10 void set(int i) { 11 arr[i >> SHIFT] |= (1 << (i & MASK)); 12 } 13 14 void clear(int i) { 15 arr[i >> SHIFT] &= ~(1 << (i & MASK)); 16 } 17 18 bool isSet(int i) { 19 return (arr[i >> SHIFT] & (1 << (i & MASK))); 20 } 21 22 private: 23 int* arr; 24 enum {INT_LEN = 32, SHIFT = 5, MASK = 0x1f}; 25 }; 26 27 bool unique(char *p) { 28 bool ch[256]; 29 memset(ch, false, sizeof(bool) * 256); 30 while (*p) { 31 if (ch[*p]) return false; 32 ch[*p] = true; 33 p++; 34 } 35 return true; 36 } 37 38 bool unique2(char *p) { 39 BitVector bv(256); 40 41 while (*p) { 42 if (bv.isSet(*p)) return false; 43 bv.set(*p); 44 p++; 45 } 46 return true; 47 }
1.2 Implement a function void reversefchar* str) in C or C++ which reverses a null-terminated string.
1 void reverse(char* str) { 2 if (str == NULL) return; 3 int n = strlen(str); 4 int i = 0, j = n - 1; 5 while (i < j) { 6 swap(str[i], str[j]); 7 i++; 8 j--; 9 } 10 }
1.3 Given two strings, write a method to decide if one is a permutation of the other。
忘了一点,就是要先确认是不是case sensitive和whitespace significant。
1 bool isPerm(char* s1, char* s2) { 2 int n1 = strlen(s1), n2 = strlen(s2); 3 if (n1 != n2) return false; 4 sort(s1, s1 + n1); 5 sort(s2, s2 + n2); 6 return strcmp(s1, s2) == 0; 7 } 8 9 bool isPerm2(char* s1, char* s2) { 10 int ch[256]; 11 memset(ch, 0, sizeof(int) * 256); 12 13 while (*s1) ch[*s1++]++; 14 while (*s2) { 15 if (--ch[*s2++] < 0) return false; 16 } 17 return true; 18 }
1.4 Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string.
1 char* replaceSpace(char* str) { 2 int b = 0; 3 char *p = str; 4 while (*p != '