Saturday, September 1, 2012

Given two string, check whether the other is permutation of first one or not. Eg: abc cba Ans: True Eg: abca abbc: Ans: False

1.take an array of 256 size,(for ascii characters),initialize with 0.
2.iterate through the both string,increment the value of array1 by 1,on position pointed by ascii value of char obtained and simultaneously
decrement the value of array2 by 1,on position pointed by ascii value of char /: 
3.finally check if at any index in array its value is not zero if its true then return false else return true.


#include<iostream>
#include <string.h>
using namespace std;
 
int ifPermutation(const char* a, const char* b)
{
if (strlen(a) != strlen(b))
return 0;
 
 
char arr[256];
memset(arr, 0, sizeof(arr));
 
 
for (int i = 0; i < strlen(a); i++)
{
arr[a[i]]++;
arr[b[i]]--;
}
 
 
for (int i = 0; i < 256; i++)
{
if (arr[i] != 0)
return 0;
}
 
 
return 1;
};
 
 
int main()
{
char* a = "abca";
char* b = "cbaa";
 
 
int res = ifPermutation(a, b);
printf("%d",res);
 
 
}
 
time complexity o(n)
space complexity o(1)

No comments :