题目:
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
思路:
使用一个数组存储每个字母出现的次数,其下标为字符值-'a',在s中出现则该字符数量加1,在t中出现则该字符次数减1,之后判断该数组若有值不为0的
项则说明两个字符串的字符出现次数不一致,返回false,否则返回true
代码:
直接使用字符串的charAt方法去获取对应位置的字符,发现此方法比较慢
class Solution {
public boolean isAnagram(String s, String t) {
int[] count1 = new int[26];
if(s.length() != t.length()){
return false;
}
for(int i = 0; i < s.length(); i++){
count1[s.charAt(i)-'a']++;
count1[t.charAt(i)-'a']--;
}
for(int i = 0; i< 26; i++){
if(count1[i] != 0){
return false;
}
}
return true;
}
}
先把字符串转变为字符数组再进行遍历,发现执行速度提升了不少
class Solution {
public boolean isAnagram(String s, String t) {
int[] count1 = new int[26];
if(s.length() != t.length()){
return false;
}
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
for(int i = 0; i < sChars.length; i++){
count1[sChars[i]-'a']++;
count1[tChars[i]-'a']--;
}
for(int i = 0; i< 26; i++){
if(count1[i] != 0){
return false;
}
}
return true;
}
}
进阶:
思路与之前差不多,但因为字符串元素类型和多少种类不固定,则需要使用map集合来存储字符值和对应的个数
仅仅对应字母的题而言,此方法很慢,但此方法可以处理包含所有unicode 字符的字符串
class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Object, Integer> map = new HashMap<>();
if(s.length() != t.length()){
return false;
}
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
for(int i = 0; i < sChars.length; i++){
if(!map.containsKey(sChars[i])){
map.put(sChars[i],1);
}else{
map.put(sChars[i],map.get(sChars[i]) + 1);
}
if(!map.containsKey(tChars[i])){
map.put(tChars[i],-1);
}else{
map.put(tChars[i],map.get(tChars[i]) - 1);
}
}
Set<Object> keys = map.keySet();
for(Object key : keys){
if(map.get(key) != 0){
return false;
}
}
return true;
}
}