编辑代码


// Method 1
function ana(a,b){
    let amap = [];
    let bmap = [];
    for (let i in a){
        if (amap[a[i]] >= 1){
            amap[a[i]] += 1;
        }
        else {
            amap[a[i]] = 1;
        }
    }
    for (let i in b){
        if (bmap[b[i]] >= 1){
            bmap[b[i]] += 1;
        }
        else {
            bmap[b[i]] = 1;
        }
    }
    for (let i in amap){
        if (amap[i] != bmap[i]) {
            return false;
        }
    }
    
    return true;
}


function sherlockAndAnagrams(s) {
    // Write your code here
    let len = s.length;
    let start = s[0]; 
    let cnt = 0;
    
    for (let i = 0; i < len; i++){
        for (let j = i + 1; j < len; j++){
            if (s[j] == s[i]) {
                cnt++;
                //console.log(i, j) // single char
                // start = s[i];
            }
            
            for (let k = 2; k < len + 1 - j; k++){
                let b = s.substring(j, j+k)
                let a = s.substring(i, i+k)
                //console.log(a,b)
                if (ana(a,b)){
                    cnt++;
                    //console.log(a,b)
                }
            }    
        }

    }
    //console.log('cnt', cnt)
    return cnt;
}


// Method Brilliant
function sherlockAndAnagrams(s) {
    let count = 0;

    // Size of our sliding window
    for (let i = 1; i < s.length; i++) {
        let found = {};
        
        // Starting index of our sliding window
        for (let j = 0; j + i <= s.length; j++) {
            let substr = s.substr(j, i);
            substr = substr.split('').sort().join('');
            if (found[substr]) {
                count += found[substr];
                found[substr]++;
            } else {
                found[substr] = 1;
            }
        }
    }

    return count;
}

// text input
5
ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel
gffryqktmwocejbxfidpjfgrrkpowoxwggxaknmltjcpazgtnakcfcogzatyskqjyorcftwxjrtgayvllutrjxpbzggjxbmxpnde
mqmtjwxaaaxklheghvqcyhaaegtlyntxmoluqlzvuzgkwhkkfpwarkckansgabfclzgnumdrojexnrdunivxqjzfbzsodycnsnmw
ofeqjnqnxwidhbuxxhfwargwkikjqwyghpsygjxyrarcoacwnhxyqlrviikfuiuotifznqmzpjrxycnqktkryutpqvbgbgthfges
zjekimenscyiamnwlpxytkndjsygifmqlqibxxqlauxamfviftquntvkwppxrzuncyenacfivtigvfsadtlytzymuwvpntngkyhw


// output
399
471
370
403
428