【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
题目比较直观,只需要检查两个字符串中,相同字符是否出现了同样的次数,并且没有多余的字符,即可;
public class Solution {
public boolean isAnagram(String s, String t) {
int[] map = new int[26];
char[] cs = s.toCharArray();
for(char c : cs) {
int x = c - 'a';
map[x] += 1;
}
cs = t.toCharArray();
for(char c : cs) {
int x = c - 'a';
if(map[x] == 0) {
return false;
}
map[x] -= 1;
}
for(int x : map) {
if(x != 0) {
return false;
}
}
return true;
}
}
利用题目中只会出现小写字母,可以使用一个26位的int数组,分别表示a~z的出现的次数;
先计算s中字符出现的次数,
然后遍历t,并减少该字符出现的次数;如果遇到某个字符,其出现次数已经被减到了0,那么该字符是在t中多出现了一次,返回false即可;
遍历完t,再检查一遍是否有字符的出现次数没有被减到0的情况;如果存在,说明该字符在s中出现的次数比在t中多;返回false;
最后返回true即可;
时间复杂度为o(n), 空间复杂度为常量;
来源:oschina
链接:https://my.oschina.net/u/922297/blog/486450