Leetcode:242.有效的字母异位词

跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
Leetcode:242.有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"

输出: true

示例 2:

输入: s = "rat", t = "car"

输出: false

在这种题型中可以将数组,set,map都可以看做是hash表,a的ASCII是97,字符串中每个值直接映射到数组的某个位置上,然后计数,最后若数组每个位置都还是0则说明是有效的字母异位词

java 复制代码
	public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())
            return false;
        int[] hash = new int[26];
        for(int i = 0; i< s.length(); i++){
            hash[s.charAt(i) - 'a']++;
        }
        for(int j = 0; j < t.length(); j++){
            hash[t.charAt(j) - 'a']--;
        }
        for(int i = 0; i < 26; i++){
            if(hash[i] != 0){
                return false;
            }
        }
        return true;
    }

因为最开始就判断了长度,所以可以在一个循环里面统计两个字符串

java 复制代码
	public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())
            return false;
        int[] hash = new int[26];
        for(int i = 0; i< s.length(); i++){
            hash[s.charAt(i) - 'a']++;
            hash[t.charAt(i) - 'a']--;
        }
        for(int i = 0; i < 26; i++){
            if(hash[i] != 0){
                return false;
            }
        }
        return true;
    }
相关推荐
Pniubi16 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊21 小时前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2521~2540题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2501~2520题目解析
java·leetcode
Pniubi2 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
悠仁さん3 天前
【C++】哈希表
c++·算法·散列表
Rain的Java大神之路3 天前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode