码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】242. Valid Anagram

时间:2015-08-20 20:44:11      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

提示:

注意题目里提示了两个输入字符串中的字符均为小写字符,因此我们可以建立一个大小为26的字典(数组),其中的对应关系为{0:a, 1:b, ..., 25:z}。用它保存每一个字母出现的次数。

对s,将对应的数字+1,而对于t,将对应的数字-1。最后考察字典的所有元素是否都为零即可判断出每个字符出现的次数是否一致。

代码:

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

【LeetCode】242. Valid Anagram

标签:

原文地址:http://www.cnblogs.com/jdneo/p/4746078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!