I was given anagram exercise, and it looked so simple that I doubt that I have something missing. The solution that I implemented is the one that I will bring shortly, and I wanted to ask you if you could think of any optimization, a change in approach, or a problem with my solution. I implemented the algorithm in Java.
Now exercise. As input, I have text, and as a result, I must return whether each line of this text is an anagram of every other line. That is, for input:
Cabin crew Huffiest Minnows Loll Cabin
house Huffy Minnov Lolls
Cabin crew shuffle a million US dollars Cabin crew shuffle a millionth city
The program should return True. To enter:
Cabin crew Huffiest Minnows Loll Cabin crew Huffiest
Minnow Lolls hi
Cabin crew shuffles a million US dollars Cabin crew shuffles a millionth city
the output should be False (due to the second line, of course).
Now, I thought, quite simply:
- I create 2 HashMap: ref and cur.
- I am parsing the first line of text by filling out the link. I will only count letters in alphabetical order.
- for every other line, I parse the line in cur and check if cur.equals (ref): if so return false
- If I get to the end of the text, this means that each line is an anagram of every other line, so I return true.
And ... that would be so. I tried it with 88,000 line input and it works pretty fast.
Any comments? Suggestions? Optimization?
Thank you very much for your help.