242 Valid Anagram

原题描述

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

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

Note:
You may assume the string contains only lowercase alphabets.

分析

如果s和t互为anagram,则他们由相同的字母组成,且对应字母的个数相同。提示使用hashtable,考虑分别将两个字符串的字母和其个数组成键值对存入map。利用map的自动排序功能,同时遍历两个map满足每个键和值都相等则是anagram。
当字符串长度不同时可以快速确定返回false,当字符串都为空串时返回true。

代码示例

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.empty() || t.empty())
            return true;
        if (s.length() != t.length())
            return false;
        else
        {
            map<char, int> records,recordt;
            for (string::iterator i = s.begin(), j = t.begin(); i != s.end(); ++i, ++j)
            {
                if (records.find(*i) == records.end())
                    records[*i] = 1;
                else
                    records[*i] += 1;
                if (recordt.find(*j) == recordt.end())
                    recordt[*j] = 1;
                else
                    recordt[*j] += 1;
            }   
            for (map<char, int>::iterator i = records.begin(), j = recordt.begin(); i != records.end(); ++i, ++j)
            {
                if(i->first != j->first || i->second != j->second)
                    return false;
            }
            return true;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值