大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
1 <= s.length, t.length <= 5 * 10^4
s
and t
consist of lowercase English letters.What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
首先先簡單的翻譯一下題目
給你兩個字串,要判斷這兩個字串是不是由相同種類跟數量的字母組成。
作法大致上是這樣
calloc
是因為他可以將動態記憶體配置的空間的值初始化為0
,如果是用malloc
的話,會不知道配置空間的初始值。calloc(26, sizeof(int))
,26
代表的是連續空間的大小,跟malloc
一樣使用完要用free()
釋放掉。class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict_s = {}
dict_t = {}
for index in range(len(s)):
if s[index] in dict_s:
dict_s[s[index]] += 1
else:
dict_s[s[index]] = 1
for index in range(len(t)):
if t[index] in dict_t:
dict_t[t[index]] += 1
else:
dict_t[t[index]] = 1
return dict_s == dict_t
bool isAnagram(char * s, char * t){
// int *dict_s = malloc(sizeof (int) * 26);
int *dict_s = calloc(26, sizeof(int));
// int *dict_t = malloc(sizeof (int) * 26);
int *dict_t = calloc(26, sizeof(int));
for (int index=0 ; index<strlen(s) ; index++){
if (dict_s[(int)(s[index])-97] != 0){
dict_s[(int)(s[index])-97]++;
} else {
dict_s[(int)(s[index])-97] = 1;
}
}
for (int index=0 ; index<strlen(t) ; index++){
if (dict_t[(int)(t[index])-97] != 0){
dict_t[(int)(t[index])-97]++;
} else {
dict_t[(int)(t[index])-97] = 1;
}
}
for (int index=0 ; index<26 ; index++){
if (dict_s[index] != dict_t[index]){
return false;
}
}
return true;
}
bool isAnagram(char * s, char * t){
// int *dict_s = malloc(sizeof (int) * 26);
int *dict_s = calloc(26, sizeof(int));
// int *dict_t = malloc(sizeof (int) * 26);
int *dict_t = calloc(26, sizeof(int));
for (int index=0 ; index<strlen(s) ; index++){
dict_s[(int)(s[index])-97]++;
}
for (int index=0 ; index<strlen(t) ; index++){
dict_t[(int)(t[index])-97]++;
}
for (int index=0 ; index<26 ; index++){
if (dict_s[index] != dict_t[index]){
return false;
}
}
return true;
}
bool isAnagram(char * s, char * t){
// int *dict_s = malloc(sizeof (int) * 26);
int *dict = calloc(26, sizeof(int));
int index_s=0, index_t=0;
while (index_s != strlen(s) || index_t != strlen(t)){
if (index_s<strlen(s)){
dict[(int)(s[index_s])-97]++;
index_s++;
}
if (index_t<strlen(t)){
dict[(int)(t[index_t])-97]--;
index_t++;
}
}
for (int index=0 ; index<26 ; index++){
if (dict[index] != 0){
return false;
}
}
return true;
}
Python
C
ver. 1
ver. 2
ver. 3
大家明天見