s="anagram", t="nagaram"
這就屬於異位詞,長度一樣,包含的字母都一樣,每個字符出現的頻率也一樣,只是順序不同而已
s="rat",t="car"
這種就不屬於異位詞,因為s中的'r'在t中沒有
思路:
1 首先看字符串長度是否一樣,不一樣則為false
2 看每個字符出現的頻率是否一樣,可以用到hash表。申請一個26長度的int數組。首先遍歷字符串s然后,將每個字符串
換算成索引后存入數組,並同時進行計數
3 遍歷字符串t,然后依次對字符對對應的數組值減一,如果出現小於0的情況則說明不匹配
代碼如下:
int isAnagram(char *s, char *t) { int freq[26]; int i, j,len_s, len_t,value; len_s = strlen(s); len_t = strlen(t); value = 0; memset(freq, 0, 26*4); if (len_s != len_t) return -1; for (i = 0; i < len_s; i++) { freq[*(s + i) - 'a']+=1; } for (j = 0; j < len_t; j++) { freq[*(t + j) - 'a']-=1; value = freq[*(t + j) - 'a']; if (value < 0) return -1; } return 1; }