LeetCode 242 有效的字母异位词 C++ 实现

1. 题目

原题链接:242. 有效的字母异位词 - 力扣(LeetCode): https://leetcode.cn/problems/valid-anagram/

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

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

  • 1 <= s.length, t.length <= 5 * 104
  • st 仅包含小写字母
示例1

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

示例2

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

2. 参考题解

// https://github.com/cc01cc/algorithm-learning/blob/master/practice/leetcode/LeetCode242_01_01.cpp
#include <iostream>
using namespace std;
class Solution
{
public:
    bool isAnagram(string s, string t)
    {
        int alphabetArray[26] = {0};
        for (int i = 0; i < s.size(); i++)
        {
            alphabetArray[s[i] - 'a']++;
        }
        for (int i = 0; i < t.size(); i++)
        {
            alphabetArray[t[i] - 'a']--;
        }

        for (int i = 0; i < sizeof(alphabetArray) / sizeof(alphabetArray[0]); i++)
        {
            if (alphabetArray[i] != 0)
                return false;
        }
        return true;
    }
};

int main()
{
    Solution solution;
    bool res = solution.isAnagram("anagram", "nagaram");
    cout << res << endl;
}

3. 解题思路

核心思想:若两个字符串为有效的字母异位词,则每个字母出现的次数应该相同,所以统计每个字符串中每个字母出现的次数即可

  1. 定义一个长度为 26 的数组,按顺序表示 26 个字母
  2. 读取第一个字符串 s ,统计每个字母出现的次数,例如 a 出现一次,alphabetArray[s[i] - 'a']++
  3. 读取第二个字符串 t ,每出现一个字母,则减去一次,例如 a 出现一次,alphabetArray[s[i] - 'a']--
  4. 若为字母异位词,则经过加减后所有字母的次数应该为 0;
  5. 遍历数组,若存在不为 0 的值,则返回 false 否则返回 true

4. 代码下载

  1. Github algorithm-learning/LeetCode242_01_01.cpp at master · cc01cc/algorithm-learning: https://github.com/cc01cc/algorithm-learning/blob/master/practice/leetcode/LeetCode242_01_01.cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零一魔法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值