CareerCup 150 (Cracking the Coding Interview)是由 Google 的前员工撰写的,一本针对程序员面试的攻略,其中囊括了许多 IT 巨头的面试流程。这本书的题目难度适中,不是很难,但是想要一次把代码写正确,却需要多多练习。
/* This is one of the solution set to CareerCup 150 problems.
*
* Problem 1.3
*
* Method 1: Test every char in str1, if it is in the str2,
* then record its index in str2 using an int array.
* Method 2: Use a int array[256], plus 1 to the array[char in str1], minus 1 to the array[char in str2],
* if the result array is not all 0, return false.
*
* Date: 19/02/2013
* Compile command: gcc-4.7 1.3.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//To decide if str1 is a permutation of str2
int isPermutation(char *str1, char *str2); // O(n^2) time, O(n) space
int isPermutation2(char *str1, char *str2); // O(n) time, O(1) space
int main()
{
char *str1 = "abcdefg";
char *str2 = "efgabcd";
if(isPermutation2(str1, str2))
printf("str1 is a permutation of str2.\n");
else
printf("str1 is not a permutation of str2.\n");
return 0;
}
int isPermutation(char *str1, char *str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
if(len1 != len2)
return 0;
int *flag = malloc(sizeof(int)*len1);
memset(flag, 0, sizeof(int)*len1);
int i, j, found;
for(i = 0; i < len1; i++)
{
found = 0;
for(j = 0; j < len1; j++)
{
if((str1[i] == str2[j]) && (flag[j] == 0))
{
flag[j] = 1;
found = 1;
break;
}
}
if(found != 1)
return 0;
}
return 1;
}
#define charCount 256
int isPermutation2(char *str1, char *str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
if(len1 != len2)
return 0;
int *flag = malloc(sizeof(int)*charCount);
memset(flag, 0, sizeof(int)*charCount);
int i;
for(i = 0; i < len1; i++)
{
flag[str1[i]]++;
}
for(i = 0; i < len1; i++)
{
flag[str2[i]]--;
}
for(i = 0; i < charCount; i++)
{
if(flag[i] != 0)
return 0;
}
return 1;
}
转载于:https://blog.51cto.com/hector/1144027