Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
- Method 1:类似使用MAP来存储出现次数
class Solution {
public boolean isAnagram(String s, String t) {
int[] count = new int[26];
int sLen = s.length();
int tLen = t.length();
if(sLen != tLen) return false;
for(int i = 0; i < sLen; i++)
count[s.charAt(i) - 'a']++;
for(int i = 0; i < tLen; i++)
count[t.charAt(i) - 'a']--;
for(int i = 0; i < 26; i++)
if(count[i] != 0) return false;
return true;
}
}
- Since it mentions that only unicode will be included, so I used a array as a map.
class Solution {
public boolean isAnagram(String s, String t) {
int[] count = new int[256];
char[] sArr = s.toCharArray();
for(int i = 0; i < sArr.length; i++){
count[sArr[i]]++;
}
char[] tArr = t.toCharArray();
for(int i = 0; i < tArr.length; i++){
count[tArr[i]]--;
}
for(int i = 0; i < 256; i++){
if(count[i] != 0) return false;
}
return true;
}
}