LeetCode 242. Valid Anagram 题解(C++)

LeetCode 242. Valid Anagram 题解(C++)


题目描述

  • Given two strings s and t, write a function to determine if t is an anagram of s.

举例

  • s = “anagram”, t = “nagaram”, return true.
    s = “rat”, t = “car”, return false.

补充

  • You may assume the string contains only lowercase alphabets.

思路

  • 首先先判断两个字符串的长度是否一样,若不一样则返回false;
  • 定义一个包含26个整数的数组cNum,用于保存每个字母出现的次数,遍历字符串s,将每个字母出现的次数记录在数组cNum里;
  • 再次遍历字符串t,若该字母对应的位置存储的值为0,则代表该字母为s没出现过或s出现过,但是已经被t之前的字母抵消,即该字母在s中无法找到想匹配的字母,返回false;若对应位置存储的值不为0,则值自减1,表示s中的该字母被抵消了一个。

代码

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

Follow out

  • What if the inputs contain unicode characters? How would you adapt your solution to such case?
  • 使用哈希表实现,在c++中可以用stl中的map实现。若按照上面的方法为unicode的每个字符都开辟一个数组元素,则该数组将会非常之大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值