您的位置:首页 > 其它

[leetcode] 242.Valid Anagram

2015-08-02 10:55 363 查看
题目:

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,判断T是不是S的字符经过调整位置得到。

思路:

只需要记录两个字符串是否出现了一样多的字符,每个字符是否出现的次数相同即可。使用数组当做hash来记录字符出现的次数。

以上。

代码如下:

class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length())return false;
else if(s.length() == 0)return true;
int dict[256];
memset(dict, 0, sizeof(dict));
int count = 0;
for(auto c : s) {
count += (dict[c] == 0)? 1 : 0;
dict[c]++;
}
for(auto c : t) {
dict[c]--;
count -= (dict[c] == 0)? 1: 0;
}
return (count == 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: