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
复制代码
这道题其实不难,作为easy的题目来说,难度还ok。
基本上无非就是用hashmap之类的进行计数,统计不同字符的出现个数。
如果出现次数相同互为异位字。
与此同理,如果连长度都不同那直接false结束。
这边我采用了数组进行统计,也是相对而言比较简单的一种方式。
代码如下:
class Solution {
private int[] S = new int[128];
private int[] T = new int[128];
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
for (int i = 0, l = s.length(); i < l; i++) {
S[s.charAt(i)]++;
}
for (int i = 0, l = t.length(); i < l; i++) {
T[t.charAt(i)]++;
}
for (int i = 0; i < 128; i++) {
if (S[i] != T[i]) return false;
}
return true;
}
}
复制代码
利用ASCII的规则,其实每个字母都有对应的数字比如A就是65,具体对应关系看下表:
所以实际上我们真正利用到的也就是65-122之间的字母,因为数组是通过index来得到对应的值。也就是说我们利用数字来对应字母,value来标记其出现次数,这样就能验证对应的字母出现个数从而方便统计。