![](/img/trans.png)
[英]Anagram of 2 string : I don't understand what is the problem with my code
[英]please explain code of anagram ,i can't understand counter array ,every value already is 0
bool isAnagram(string c, string d){
if(c.length()!=d.length())
return false;
int count[256]={0};
for(int i=0;i<c.length();i++){
count[c[i]]++;
}
for(int i=0;i<d.length();i++){
count[d[i]]--;
}
for(int i=0;i<c.length();i++)
if(count[c[i]]!=0)
return false;
return true;
}
請解釋 anagram 的代碼,我無法理解計數器數組,每個值都已經是 0,所以必須包含每個索引,它是否明智地存儲 asci 值
這是一個類似的問題,但這說明了計數器 arrays 的使用:
int makeAnagram(string a, string b) {
vector<int> freq(26,0);
for(int i=0;i<a.length();i++) freq[a[i] - 'a']++;
for(int j=0;j<b.length();j++) freq[b[j] - 'a']--;
int sum = 0;
for(int i=0;i<26;i++) sum += abs(freq[i]);
return sum;
}
計數器數組用於“計數”值(我將其命名為 freq 以表示頻率)。 這里freq[0]
the frequency/count of the char 'a'
相同,因為'a' - 'a' = 0
。 這也是處理 ascii 轉換的方法以及為什么我的頻率向量大小為 26 的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.