哈希表-有效字母异位词

题目描述:

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

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

思路:在这题使用哈希表的方法,这里使用数组当作一个哈希表,遍历字符串,利用ascill值计算出出现的字母在数组中对应的位置,并且进行计数

力扣上242题:https://leetcode.cn/problems/valid-anagram/

class Solution {
public:
    bool isAnagram(string s, string t) {
        int hash[26] = {0};
        for(int i = 0;i < s.size(); i++)
        {
            hash[s[i] - 'a'] ++;
        }
        for(int i = 0;i < t.size(); i++)
        {
            hash[t[i] -'a'] --;
        }
        for(int i = 0;i < 26;i ++)
        {
            if(hash[i] != 0)
            {
                return false;
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_62859191/article/details/129034919