简体   繁体   中英

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

This is a similar question but this illustrates the use of counter 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). Here freq[0] is the same as the frequency/count of the char 'a' because 'a' - 'a' = 0 . This is also how you can cope with the ascii conversion and why my freq vector is of size 26.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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