哈希表 242.有效的字母异位词

考点

  1. array可以作为实现哈希表的一种数据结构
  2. 字母的ASCII码

解题思路

26个字母意味着array的大小为26,a-z的ASCII是连续的,所以array[0]对应a,array[1]对应b…
先遍历s,如果s中有a,则array[0]加1…
再遍历t,如果t中有a,则array[0]减1…
最后如果array中的所有元素都为0,则可认为s与t是异位词

代码

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

        for(int i=0; i<26; i++)
        {
            if(record[i] != 0)
                return false;
        }

        return true;
    }
};

wirtten by myself

/*
 * @lc app=leetcode.cn id=242 lang=cpp
 *
 * [242] 有效的字母异位词
 */

// @lc code=start
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;

class Solution {
public:
    bool isAnagram(string s, string t) 
    {
        unordered_map <char,int> mapS, mapT;
        mapS = insertWord(s,mapS);
        mapT = insertWord(t,mapT);
        
        
        for(auto key: (mapS.size() >= mapT.size()) ? mapS : mapT)
        {
            if (mapS[key.first] != mapT[key.first])
                return false;
        }

        return true;
    }

    unordered_map <char,int> insertWord(string word, unordered_map<char, int> mapWord)
    {
        for (int i=0; i<word.size(); i++)
        {
            mapWord[word[i]]++;
        }
        return mapWord;
    }

    void traverseUnorderedMap(unordered_map<char, int> mapWord)
    {
        for (auto kv: mapWord)
        {
            cout << kv.first << " -> " << kv.second << endl;
        }
    }
};
// @lc code=end

int main()
{
    string s = "anagram";
    string t = "nagaram";

    bool ans;
    Solution so;
    ans = so.isAnagram(s,t);
    cout << ans << endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值