LeetCode 242 Valid Anagram

来源:互联网 发布:php json格式化输出 编辑:程序博客网 时间:2024/06/15 05:33

题目:

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 ,写一个函数判断 s 能否通过交换字母位置来组成 t。

s 和 t 都只包含 小写字母。

对于 s,和 t ,分别统计其中每一个字母出现的次数,之后比较 s 和 t 的包含字母及数量是否一致即可。

代码如下:

class Solution {public:    bool isAnagram(string s, string t) {        map<char, int> dic1, dic2;        for (char c : s) dic1[c] ++;        for (char c : t) dic2[c] ++;        return dic1 == dic2;    }};