Description:
Given two strings s and t , write a function to determine if t is an anagram of s.
Example :
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Description Title :
Given two strings s and t, t write a function to determine whether the ectopic letters of the word s.
Examples:
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You can assume that the string contains only lowercase letters.
Advanced:
If the input string contains unicode characters how to do? Can you adjust your solution to deal with this situation?
Thinking :
maintaining an array of length 26, the values of s and t is stored in an array
if it contains Unicode, can maintain a map, the number of occurrences stored in this case space complexity is O (n)
time complexity of O (n) space complexity O (1)
Code :
C ++ :
class Solution {
public:
bool isAnagram(string s, string t) {
int *a = new int[26]();
if (s.size() != t.size()) return false;
for (int i = 0; i < s.size(); i++) {
a[s[i] - 'a']++;
a[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) if (a[i]) return false;
return true;
}
};
Java:
class Solution {
public boolean isAnagram(String s, String t) {
int a[] = new int[26];
if (s.length() != t.length()) return false;
for (int i = 0; i < s.length(); i++) {
a[s.charAt(i) - 'a']++;
a[t.charAt(i) - 'a']--;
}
for (int i = 0; i < 26; i++) if (a[i] != 0) return false;
return true;
}
}
Python:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)