CareerCup 150 (Cracking the Coding Interview)是由 Google 的前员工撰写的,一本针对程序员面试的攻略,其中囊括了许多 IT 巨头的面试流程。这本书的题目难度适中,不是很难,但是想要一次把代码写正确,却需要多多练习。

这本书盛名已久,我就不多介绍了,书中提供的解答是 Java 版本的,我自己喜欢用 C,所以在这里记录 C 语言版本的解答,希望和大家多多交流。
------------------------------- 1.3.c -----------------------
题目我就不在这里写了,网上到处都有的。
 
  
  1. /* This is one of the solution set to CareerCup 150 problems.

  2. *

  3. * Problem 1.3

  4. *

  5. * Method 1: Test every char in str1, if it is in the str2,

  6. * then record its index in str2 using an int array.

  7. * Method 2: Use a int array[256], plus 1 to the array[char in str1], minus 1 to the array[char in str2],

  8. * if the result array is not all 0, return false.

  9. *

  10. * Date: 19/02/2013

  11. * Compile command: gcc-4.7 1.3.c

  12. */

  13. #include <stdio.h>

  14. #include <string.h>

  15. #include <stdlib.h>

  16. //To decide if str1 is a permutation of str2

  17. int isPermutation(char *str1, char *str2); // O(n^2) time, O(n) space

  18. int isPermutation2(char *str1, char *str2); // O(n) time, O(1) space

  19. int main()

  20. {

  21. char *str1 = "abcdefg";

  22. char *str2 = "efgabcd";

  23. if(isPermutation2(str1, str2))

  24.        printf("str1 is a permutation of str2.\n");

  25. else

  26.        printf("str1 is not a permutation of str2.\n");

  27. return 0;

  28. }

  29. int isPermutation(char *str1, char *str2)

  30. {

  31. int len1 = strlen(str1);

  32. int len2 = strlen(str2);

  33. if(len1 != len2)

  34. return 0;

  35. int *flag = malloc(sizeof(int)*len1);

  36.    memset(flag, 0, sizeof(int)*len1);

  37. int i, j, found;

  38. for(i = 0; i < len1; i++)

  39.    {

  40.        found = 0;

  41. for(j = 0; j < len1; j++)

  42.        {

  43. if((str1[i] == str2[j]) && (flag[j] == 0))

  44.            {    

  45.                flag[j] = 1;

  46.                found = 1;

  47. break;

  48.            }

  49.        }

  50. if(found != 1)

  51. return 0;

  52.    }

  53. return 1;

  54. }

  55. #define charCount 256

  56. int isPermutation2(char *str1, char *str2)

  57. {

  58. int len1 = strlen(str1);

  59. int len2 = strlen(str2);

  60. if(len1 != len2)

  61. return 0;

  62. int *flag = malloc(sizeof(int)*charCount);

  63.    memset(flag, 0, sizeof(int)*charCount);

  64. int i;

  65. for(i = 0; i < len1; i++)

  66.    {

  67.        flag[str1[i]]++;

  68.    }

  69. for(i = 0; i < len1; i++)

  70.    {

  71.        flag[str2[i]]--;

  72.    }

  73. for(i = 0; i < charCount; i++)

  74.    {

  75. if(flag[i] != 0)

  76. return 0;

  77.    }

  78. return 1;

  79. }