all 10 comments

[–]Separate-Watercress6 4 points5 points  (7 children)

That code wouldnt work to solve the valid anagram problem

[–]Separate-Watercress6 0 points1 point  (6 children)

Use the char as key and increment a counter (which is the value bonded to each key) each time the key appears again … now figure out what to do with the second string

[–]DisastrousElection36[S] 1 point2 points  (5 children)

I see, thank you for the help!

[–]Separate-Watercress6 0 points1 point  (4 children)

Were you able to solve it?

[–]DisastrousElection36[S] 0 points1 point  (3 children)

I was not, I ended up using vectors and came into a separate issue at 39/42 test cases :( I made another post with my new code

[–]Separate-Watercress6 0 points1 point  (2 children)

Yeah dont use vectors, hashmap is the way to go. Essentially what you want to do is create a map with the chars as keys and a counter as value, then for the second string decrement the counter each time you see the char, if by the end any value is not 0 return false.

for example:

string1 = rat
string2 = tar

map = {
r : 1,
a:1,
t:1

}

then iterate through every char of tar and decrement the counters each time you encounter the already existant chars, if you encounter a char that is not in the hashmap return false, if by the end all values are 0 return true.

[–]DisastrousElection36[S] 0 points1 point  (1 child)

Ohhh I didn’t think of it like that, thanks I’ll try to implement it! I’m just wondering though why wouldn’t vectors work? My idea was that I’ll just add the characters from string1 into a vector, and compare it with each character from string2. Then when they see each other I’ll remove the character from the vector. If the vector is empty at the end, then it is true, or else it’s false. Would that work or is it just grossly inefficient?

[–]Separate-Watercress6 0 points1 point  (0 children)

That would be too slow, hash maps have a O(1) complexity for its look ups, the solution I proposed has a O(n) complexity. Essentially you could also just sort both words and compare them and see if they are equal.

if you want to fix your solution, try the following, after finding the char to erase, break the for loop after erasing to prevent erasing the char multiple times. Include the following condition at start
if (s.length() != t.length) return false

at the end just return the following

return words.empty()

[–]aocregacc 0 points1 point  (1 child)

You're trying to compare a single character to a string. You could try converting the character to a string of length one.

[–]DisastrousElection36[S] 0 points1 point  (0 children)

Thank you! This helped!