notes/OJ notes/pages/Leetcode Valid-Anagram.md
2022-09-06 20:22:48 +08:00

93 lines
1.9 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:
##### 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;
}
};
```