[LeetCode] Valid Anagram

242. Valid Anagram

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?

  • we can use map rather then integer array
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool isAnagram(string s, string t) {
int arr[26]{0};
for(auto& ch : s) ++arr[ch-'a'];
for(auto& ch : t) --arr[ch-'a'];

for(int i = 0; i < 26; i++)
if(arr[i]) return false;
return true;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/valid-anagram/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.