Thursday, 11 February 2016

Find whether two given strings are permutations of each other


Write a program to find whether two given strings are permutations of each other.  A string str1 is a permutation of str2 if all the characters in str1 appear the same number of times in str2 and str2 is of the same length as str1.


Solution:

#include<stdio.h> int main(){ int acount[128] = {0}, bcount[128] = {0}, c = 0; char a[100]; char b[100]; scanf("%s",a); scanf("%s",b); //now take every character from string 'a' and using ASCII value increment corresponding index in array 'acount' while (a[c] != '\0') { acount[(int)a[c]]++; c++; } c = 0; //now take every character from string 'b' and using ASCII value increment corresponding index in array 'bcount' while (b[c] != '\0') { bcount[(int)b[c]]++; c++; } for (c = 0; c < 128; c++) { //if any single character also mismatch then return no if (acount[c] != bcount[c]) { printf("no"); return 0; } } //satisfy criteria so return true printf("yes"); return 0; }

No comments:

Post a Comment