438. Find All Anagrams in a String (Hash Table)

class Solution { public: bool isAnagram(string s, string t) { unordered_map<char, int> m; for (char & ss: s) m[ss]++; for (char & tt: t){ if (m.find(tt) == m.end()) return false; else m[tt]--; } for (auto & it: m){ if (it.second != 0) return false; } return true; } vector<int> findAnagrams(string s, string p) { int length = p.size(); vector<int> res; for (size_t start = 0; start < s.size(); start++){ string temp = s.substr(start, length); if (isAnagram(temp, p)) res.push_back(start); } return res; } };
Solution using two hashtables... TLE. But passed 34/36 tests.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.