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

廉价感情. 提交于 2019-11-26 23:45:55

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的每个字符都开辟一个数组元素,则该数组将会非常之大。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!