notes/OJ notes/pages/Leetcode Valid-Anagram.md
2022-07-07 21:24:34 +08:00

85 lines
2 KiB
Markdown

# Leetcode Valid-Anagram
#### 2022-06-14 13:36
---
##### Algorithms:
#algorithm #hash_table
##### Data structures:
#DS #array
##### Difficulty:
#leetcode #coding_problem #difficulty-easy
##### Related topics:
```expander
tag:#array tag:#hash_table
```
- [[Leetcode First-Unique-Character-In-a-String]]
- [[Leetcode Ransom-Note]]
##### Links:
- [Link to problem](https://leetcode.com/problems/valid-anagram/)
___
### 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:**
```markdown
**Input:** s = "anagram", t = "nagaram"
**Output:** true
```
**Example 2:**
```markdown
**Input:** s = "rat", t = "car"
**Output:** false
```
#### Constraints
- `1 <= s.length, t.length <= 5 * 104`
- `s` and `t` 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](https://www.cprogramming.com/tutorial/unicode.html) and this [answer](https://stackoverflow.com/questions/3010739/how-to-use-unicode-in-c/3019339#3019339)
### Solution
```cpp
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;
}
};
```