Cover image for Classic 150 Interview Questions P242 Valid Anagram

Classic 150 Interview Questions P242 Valid Anagram


Timeline

Timeline

2025-11-13

init

Hash table

Problem:

Use a hash table to record the count of each letter, then tally.

12345678910111213141516171819202122232425262728
#include <string>#include <unordered_map>using std::string;using std::unordered_map;class Solution {    public:	bool isAnagram(string s, string t)	{		if (s.size() != t.size()) return false;				unordered_map<char, int> smap;				for (char &ch : s)			smap[ch]++;		for (char &ch : t) {			if (!smap.count(ch))				return false;			smap[ch]--;						if (smap[ch] < 0)				return false;		}		return true;	}};
Loading comments…