#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
using namespace std;
static bool isanagram(string a, string b);
int main(void)
{
int i,n,j,s;
cin >> n;
string a, b;
cin >> a >> b;
if(!isanagram(a,b)) cout << "False" << endl;
else cout << "True" << endl;
return 0;
}
static bool isanagram(string a, string b)
{
int i, j, size, s=0;
size = a.size();
bool k;
for(i=0;i<size;i++)
{
k=false;
for(j=0;j<size;j++)
{
if(a[i] == b[j]) { k = true; break; }
}
if(k==true) s+=1;
}
cout << a[2] << b[2] << endl;
if(s == size) return true;
else return false;
}
I don’t know where exactly is the problem so i just pasted the whole code.
It should be a simple program capable for finding if two strings are anagrams, but it’s not working and i don’t know why. I used pointers in the program so thought the might be the problem and removed them, i removed other things additionally but still it’s not working. If you can give it a look-see and tell me some idea where i might’ve gone wrong with my code ?
Thank you in advance.
First things first: don’t declare the method
static. It’s a confusing keyword at the best of times given all the roles it can fulfill… so reserve for times when you really have to (method or attribute of a class that is not tied to any instance for example).Regarding the algorithm: you’re nearly there, but presence only is not sufficient, you need to take the number of characters in account too.
Let’s do it simply:
Let’s see it at work:
anagram("abc","cab")count = [0, 0, ...., 0]i == 0>['a': 1, 'c': -1]i == 1>['a': 0, 'b': 1, 'c': -1]i == 2>['a': 0, 'b': 0, 'c': 0 ]And the second loop will pass without any problem.
Variants include maintaining 2 counts arrays (one for each strings) and then comparing them. It’s slightly less efficient… does not really matter though.