-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path242.valid-anagram.cpp
More file actions
47 lines (44 loc) · 1.17 KB
/
242.valid-anagram.cpp
File metadata and controls
47 lines (44 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Tag: Hash Table, String, Sorting
// Time: O(N)
// Space: O(1)
// Ref: -
// Note: -
// 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.
//
// 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 and t consist of lowercase English letters.
//
//
// Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
//
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
int n = s.size();
vector<int> count(26, 0);
for (int i = 0; i < n; i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
};