【字符串】【打卡122天】:242. 有效的字母异位词

1、题目描述

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

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

2、算法分析

int是32位的,英文字母有26个。所以可以使用int[] count = new int[26];存储字符串中出现字母的个数。

具体的话,

count[s.charAt(i) - 'a']:s.charAt(i) - 'a',求字母之间的ascell之间的差值。

小写字母asell范围:a-z:97-122。

count[s.charAt(i) - 'a']++:求的是字符串中对应字母的个数。

最后遍历count数组。

具体看代码:

3、代码实现

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        int[] count = new int[26];
        for(int i = 0;i < s.length();i++){
            // 计数s字符串中的个数
            count[s.charAt(i) - 'a']++;
            // 反正是初始化为0.负数也行的
            count[t.charAt(i) - 'a']--;
        }
        // 最后遍历并判断。
        for(int i = 0;i < count.length;i++){
            if(count[i] != 0){
                return false;
            }
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/121599611