Javascript solution-sharing


  • 0
    C
    /**
     * @param {string} s
     * @param {string} t
     * @return {boolean}
     */
    var isAnagram = function(s, t) {
        // var s_arr = s.split('');
        // var t_arr = t.split('');
        // var hashMap = {};
        // for(var i=0; i<s.length; i++){
        //     if(hashMap[s[i]]===undefined){
        //         hashMap[s[i]] = 1;
        //     }else{
        //         hashMap[s[i]]++;
        //     }
        // }
        // for(i=0; i<t.length; i++){
        //     if(hashMap[t[i]]>0){
        //         hashMap[t[i]]--;
        //     }else{
        //         return false;
        //     }
        // }
        // return true; 子集
        var s_arr = s.split('');
        var t_arr = t.split('');
        var s_fb = s_arr.sort().join('');
        var t_fb = t_arr.sort().join('');
        return s_fb==t_fb?true:false;
    };

  • 0
    R

    Alternative JS solution:

    var isAnagram = function(s, t) {
        if(s.length != t.length) {
            return false;
        }
        
        var count = [];
        for(var q = 0; q < 26; q++)
            count.push(0);
    
        for(var i = 0; i < s.length; i++) {
            count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
            count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--;
        }
        
        
        var bl = true;
        
        count.forEach(function(v) {
            if(v !== 0) {
                bl = false;
            }
        });
        
        return bl;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.