242. Valid Anagram
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
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?
思路:
记录第一个数组每个元素出现的次数,然后去对比另一个数组。
代码:
java:
class Solution {
/*public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] m1 = new int[128];
int[] m2 = new int[128];
char[] ss = s.toCharArray();
char[] ts = t.toCharArray();
for (int i = 0; i < ss.length; i++) {
m1[ss[i]] += 1;
m2[ts[i]] += 1;
}
for (int i = 0; i < 128; i++){
if(m1[i] != m2[i]) return false;
}
return true;
}*/
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] m = new int[128];
char[] ss = s.toCharArray();
char[] ts = t.toCharArray();
for (int i = 0; i < ss.length; i++) {
m[ss[i]]++;
}
for (int i = 0; i < ts.length; i++){
m[ts[i]]--;
if (m[ts[i]] < 0) return false;
}
return true;
}
}