• 45.4%

https://leetcode.com/problems/valid-anagram/?tab=Description

Given two strings s and t, write a function to determine if t is an anagram of s.

Note:

You may assume the string contains only lowercase alphabets.

https://discuss.leetcode.com/topic/20303/2-c-solutions-with-explanations

2 C++ Solutions with Explanations

Hash Table

This idea uses a hash table to record the times of appearances of each letter in the two strings s and t. For each letter in s, it increases the counter by 1 while for each letter in t, it decreases the counter by 1. Finally, all the counters will be 0 if they two are anagrams of each other.

The first implementation uses the built-in unordered_map and takes 36 ms.

Since the problem statement says that “the string contains only lowercase alphabets”, we can simply use an array to simulate the unordered_map and speed up the code. The following implementation takes 12 ms.

Sorting

For two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as here). However, it takes much longer time — 76 ms in C++.

https://discuss.leetcode.com/topic/20831/python-solutions-sort-and-dictionary

Python solutions (sort and dictionary).

https://discuss.leetcode.com/topic/23973/0ms-c-solution-o-n-time

0ms C++solution,O(n)time

https://discuss.leetcode.com/topic/20485/share-my-java-solution

Share my java solution

https://discuss.leetcode.com/topic/20314/accepted-java-o-n-solution-in-5-lines

Accepted Java O(n) solution in 5 lines

The idea is simple. It creates a size 26 int arrays as buckets for each letter in alphabet. It increments the bucket value with String s and decrement with string t. So if they are anagrams, all buckets should remain with initial value which is zero. So just checking that and return