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表aASCII是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;
    }
相关推荐
Jay_See2 小时前
Leetcode——239. 滑动窗口最大值
java·数据结构·算法·leetcode
爱爬山的老虎1 天前
【面试经典150题】LeetCode121·买卖股票最佳时机
数据结构·算法·leetcode·面试·职场和发展
雾月551 天前
LeetCode 914 卡牌分组
java·开发语言·算法·leetcode·职场和发展
想跑步的小弱鸡1 天前
Leetcode hot 100(day 4)
算法·leetcode·职场和发展
Fantasydg1 天前
DAY 35 leetcode 202--哈希表.快乐数
算法·leetcode·散列表
jyyyx的算法博客1 天前
Leetcode 2337 -- 双指针 | 脑筋急转弯
算法·leetcode
ゞ 正在缓冲99%…1 天前
leetcode76.最小覆盖子串
java·算法·leetcode·字符串·双指针·滑动窗口
惊鸿.Jh1 天前
【滑动窗口】3254. 长度为 K 的子数组的能量值 I
数据结构·算法·leetcode
想跑步的小弱鸡1 天前
Leetcode hot 100(day 3)
算法·leetcode·职场和发展
爱的叹息2 天前
RedisTemplate 的 6 个可配置序列化器属性对比
算法·哈希算法