南朝四百八十寺
多少樓臺煙雨中
前言
本題摘自LeetCode第242題,有效的字母異位詞,
題目描述
給定兩個字符串 s 和 t ,編寫一個函數來判斷 t 是否是 s 的字母異位詞。
事例1:
輸入: s = "anagram", t = "nagaram"
輸出: true
事例2:
輸入: s = "rat", t = "car"
輸出: false
解題思想
1.初始化兩個數組(理解爲哈希表),對應26個英文字母,開始值都爲0
int a[26] = {0};
int b[26] = {0};
2.分別遍歷s、t字符串的中的字符,給字符在數組中的位置值進行加加操作
3.對比a、b數組中的值是否一致
C語言代碼實現
BOOL isVaildAgment(char *s, char *t) {
int lengthS = strlen(s);
int lengthT = strlen(t);
int a[26] = {0};
int b[26] = {0};
for (NSInteger i = 0; i < lengthS; i++) {
int index = s[i]-'a';
a[index] = 1;
}
for (NSInteger i = 0; i < lengthT; i++) {
int index = t[i]-'a';
b[index] = 1;
}
for (NSInteger i = 0; i < 26; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}