简体   繁体   English

请解释 anagram 的代码,我看不懂计数器数组,每个值都已经是 0

[英]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;
}

please explain code of anagram,i can't understand counter array,every value already is 0,so every index must be included,is it storing asci value wise请解释 anagram 的代码,我无法理解计数器数组,每个值都已经是 0,所以必须包含每个索引,它是否明智地存储 asci 值

This is a similar question but this illustrates the use of counter arrays:这是一个类似的问题,但这说明了计数器 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;
}

A counter array is used to "count" values (I named it freq for frequency).计数器数组用于“计数”值(我将其命名为 freq 以表示频率)。 Here freq[0] is the same as the frequency/count of the char 'a' because 'a' - 'a' = 0 .这里freq[0] the frequency/count of the char 'a'相同,因为'a' - 'a' = 0 This is also how you can cope with the ascii conversion and why my freq vector is of size 26.这也是处理 ascii 转换的方法以及为什么我的频率向量大小为 26 的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM