JAVA版本
思路:
该题用的是hash表的解法。
hash表一种有三种使用方法:
1.数组
2.Set
3.Map
解法一:
使用数组方式来解决问题,使用数组的条件是,当hash的范围控时,如本题的hash大小为26,所以可以使用数组,同时数组中不用跟字母的ASCLL相对于,只要一个字母对应一个位置即可。
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()){
return false;
}
int [] arr = new int[26];
for (int i=0;i<s.length();i++){
arr[s.charAt(i) - 'a']++; //s.charAt()方法是得到字符串里面的单个字符,-'a'的目的是取到 0 -26的范围之内
//++的意思是出现相同的,数组对应的值+1;
}
for (int i=0;i<t.length();i++){
arr[t.charAt(i) - 'a']--;
}
for (int a : arr){
if (a!=0){ //增强for循环判断,只要数组中有一个不等于0说明不是异位,结束。
return false;
}
}
return true;
}
}
解法二:
该解法使用map来一一对应,主要思路是在力扣的解题方法中看到的
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> table = new HashMap<Character, Integer>(); //Map集合的声明使用方式 ,字符作为key,出现个数作为value
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) + 1); //getOrDefault(ch, 0) + 1的意思是 若对应的字符没有对应的key值就返回0,若有就是原有值增一。
}
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
if (table.get(ch) < 0) { //根据键来返回值
return false;
}
}
return true;
}
}
解法三:
对字符串排序,然后比较是否相同,此处不再写。