描述
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.
分析
哈希表的使用啦
解决方案1(C)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| bool isAnagram(char* s, char* t) { if(strlen(s) != strlen(t)){ return false; } int hash[256] = {}; char *now = s; while(*now){ hash[*now++]++; } now = t; while(*now){ if(hash[*now] > 0){ hash[*now++]--; }else{ return false; } } return true; }
|
解决方案2(Python)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from collections import defaultdict class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False hash_table = defaultdict(int) for i in s: hash_table[i] += 1 for i in t: if hash_table[i] > 0: hash_table[i] -= 1 else: return False return True
|
相关问题