题目描述
Given two strings s and t , write a function to determine if t is an anagram of s.
题目大意:给定两个字符串 s 和 t ,判断 t 是否是 s 中的字符变换顺序得到的。如果是返回True,否则返回False
样例
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
python解法
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): return False
d1, d2 = {}, {}
for i in s:
if i in d1:d1[i] += 1
else: d1[i] = 1
for i in t:
if i in d2: d2[i] += 1
else: d2[i] = 1
for i in s:
if i not in t or d1[i] != d2[i]:
return False
return True
Runtime: 60 ms, faster than 60.76% of Python3 online submissions for Valid Anagram.
Memory Usage: 13.9 MB, less than 15.63% of Python3 online submissions for Valid Anagram.
题后反思:无
C语言解法
int cmp(const void *a, const void *b)
{
return *(char*)a - *(char*)b;
}
bool isAnagram(char * s, char * t){
if (strlen(s)!=strlen(t))
return false;
qsort(s, strlen(s), sizeof(char), cmp);
qsort(t, strlen(s), sizeof(char), cmp);
for (int i=0;i<strlen(s);i++)
{
if (s[i] != t[i])
return false;
}
return true;
}
Runtime: 88 ms, faster than 24.48% of C online submissions for Valid Anagram.
Memory Usage: 7.4 MB, less than 25.00% of C online submissions for Valid Anagram.
题后反思:
- 测试样例中应该是有较大的的数据,导致使用排序然后依次比较的方法耗时较长。
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步