This is a program that to solve the following question "Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings". In the end, both strings should have the same letters and same frequency of each letter. For e.g., String A = ccda String B = dcac My logic is to replace the letter that are same in both strings with a dummy string say "0". So when I count the number of letter in each string that is not equal to "0", it gives me the number of deletion. But I don't know why this fails for certain cases.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int count =0;
const char dummy= '0';
int i =0, j=0;
char* a = (char *)malloc(512000 * sizeof(char));
scanf("%s",a);
char* b = (char *)malloc(512000 * sizeof(char));
scanf("%s",b);
for (i=0;a[i]!= '\0' ;i++){
for(j=0; b[j]!= '\0';j++){
if (a[i]==b[j]){
a[i]= dummy;
b[j]= dummy;
}
}
}
for (i=0;a[i]!= '\0' ;i++){
if(a[i]!= dummy){
count = count+1;
}
}
for (i=0;a[i]!= '\0' ;i++){
if(b[i]!= dummy){
count = count+1;
}
}
printf("%d",count);
return 0;
}
One of the test case it failed was String A : fcrxzwscanmligyxyvym String B : jxwtrhvujlmrpdoqbisbwhmgpmeoke Result given : 22 Expected result : 30
Can anyone please point me the error here. Please, thanks in advance!
You've an error in your code - invalid condition in second loop.
for (i=0;a[i]!= '\0' ;i++){
if(a[i]!= dummy){
count = count+1;
}
}
for (i=0;a[i]!= '\0' ;i++){
^^^^
if(b[i]!= dummy){
count = count+1;
}
}
In marked point should be b[i]
rather than a[i]
.
Minor nitpicking: since you're learning to code, try to get few useful habbits as you go. Code should be pretty (not very pretty, mind you, but ascethic) - it helps to ease reading for both you and everyone else. Consequence matters. If you do spaces around operators, do it everywhere. Layout matters. All of that would help you notice your (common to pros as well, they just find it sooner) mistake. Also there's a better algorithm in terms of running performance. :)