notes/OJ notes/pages/Leetcode Valid-Anagram.md

93 lines
1.9 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Leetcode Valid-Anagram
#### 2022-06-14 13:36
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
#algorithm #hash_table
2022-06-14 23:33:35 +08:00
##### Data structures:
2022-09-03 15:41:36 +08:00
#DS #array
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
2022-09-06 20:22:48 +08:00
#leetcode #coding_problem #difficulty_easy
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [Link to problem](https://leetcode.com/problems/valid-anagram/)
2022-09-03 15:41:36 +08:00
---
2022-06-14 23:33:35 +08:00
### Problem
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
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?
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#### Examples
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
**Example 1:**
```markdown
**Input:** s = "anagram", t = "nagaram"
**Output:** true
```
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
**Example 2:**
```markdown
**Input:** s = "rat", t = "car"
**Output:** false
```
#### Constraints
2022-09-03 15:41:36 +08:00
- `1 <= s.length, t.length <= 5 * 104`
- `s` and `t` consist of lowercase English letters.
2022-06-14 23:33:35 +08:00
### 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;
}
};
2022-09-03 15:41:36 +08:00
```