Invn1234's blog

By Invn1234, history, 15 months ago, In English

Given 2 strings ,determine if they are anagrams of each other.

example :

input:

listen silent

output:

True

  • Vote: I like it
  • -22
  • Vote: I do not like it

| Write comment?
»
15 months ago, # |
Rev. 3   Vote: I like it +7 Vote: I do not like it

Sort the strings and check if they are equal.

Code
»
15 months ago, # |
  Vote: I like it +1 Vote: I do not like it

I suggest you use hashing. A good hashing function in this case is adding the characters, since anagrams will result in the same sum!

int hash(string s) {
  int sum = 0;
  for (auto c : s) sum += c;
  return sum;
}

bool anagram(string s, string t) {
  return hash(s) == hash(t);
}

No way this goes wrong!

»
15 months ago, # |
Rev. 3   Vote: I like it +3 Vote: I do not like it

I think this code helps with your problem, although it's a bit long, it is easily understandable and a brute-force solution.

Code

Hope you find it easy...