[leetcode]242. Valid Anagram
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.
判断的你两个字符串是否由相同的字符组成
解法1:
排序,时间复杂度O(N log N)
1 class Solution(object): 2 def isAnagram(self, s, t): 3 return sorted(s) == sorted(t) 4
解法2:
用字典统计s中每个字母出现的次数,然后对照t中字母出现的次数,不匹配返回False,O(N)
1 class Solution(object): 2 def isAnagram(self, s, t): 3 d = collections.Counter(s) 4 for c in t: 5 d[c] -= 1 6 for val in d.values(): 7 if val != 0: 8 return False 9 return True
C语言:
1 bool isAnagram(char* s, char* t) { 2 int len_s,len_t; 3 len_s=strlen(s); 4 len_t=strlen(t); 5 if(len_s!=len_t) return false; 6 int *flag = malloc(sizeof(int)*26); 7 for(int i=0;i<26;i++) 8 flag[i] = 0; 9 for(int i=0;i<len_s;i++){ 10 flag[s[i]-'a'] += 1; 11 flag[t[i]-'a'] -= 1; 12 } 13 for(int i=0;i<26;i++) 14 if(flag[i] != 0) { 15 free(flag); 16 return false; 17 } 18 free(flag); 19 return true; 20 }