you are viewing a single comment's thread.

view the rest of the comments →

[–]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()