242. Valid Anagram
哈希表:可以拿数组当哈希表来用,但哈希值不要太大
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
逻辑分析:
暴力解法:
1.双层循环,外层s,内层t
2.不断寻找 t 中数组是否有 s 当前字母(注意判断重复情况),条件为否返回false,退出循环
3.返回 true
更优解法:
hash底层结构为数组+链表,或者数组+红黑树。所以数组就是简单的hash
1.新建长度为26的数据
2.遍历 s ,字母出现,将数组中对应下标的值加1(下标为字母的ascii码减去a的ascii码)
3.遍历 t ,字母出现,将数组中相应下标对应的值减1
4.遍历数组,遇到不为0的则返回false,否则返回true
JAVA代码实现:
class Solution {
public boolean isAnagram(String s, String t) {
int[] records = new int[26];
//s放入数据对应值
for(char c:s.toCharArray()){
records[c-'a']+=1;
}
//t消减字符对应值
for(char c:t.toCharArray()){
records[c-'a']-=1;
}
//判断是否完全为0
for(int i=0;i<records.length;i++){
if(records[i]!=0){
return false;
}
}
return true;
}
}