首页 > 其他 > 详细

【LeetCode】242. Valid Anagram

时间:2015-08-20 20:42:36      阅读:182      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!