1.9 KiB
Leetcode Valid-Anagram
2022-06-14 13:36
Algorithms:
#algorithm #hash_table
Data structures:
#DS #array
Difficulty:
#leetcode #coding_problem #difficulty-easy
Related topics:
Links:
Problem
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Examples
Example 1:
**Input:** s = "anagram", t = "nagaram"
**Output:** true
Example 2:
**Input:** s = "rat", t = "car"
**Output:** false
Constraints
1 <= s.length, t.length <= 5 * 104
s
andt
consist of lowercase English letters.
Thoughts
The difference between this and Leetcode Ransom-Note is that ransom note checks the hash table one way, and this one is bidirectional, which means not only hash map has to be >= 0, it also has to be <= 0, which results in it can only be 0.
[!tip]- To understand that Compare this solution with Leetcode Ransom-Note#Solution to better understand what I mean.
Follow up question: Refer to this site and this answer
Solution
class Solution {
public:
bool isAnagram(string s, string t) {
int hashTable[26] = {};
for (char c : s) {
hashTable[c - 'a']++;
}
for (char c : t) {
hashTable[c - 'a']--;
}
for (int i : hashTable) {
if (i != 0) {
return false;
}
}
return true;
}
};