jzhangnu / Leetcode-JS-Solutions

:tropical_drink: Leetcode solutions using JavaScript.
52 stars 7 forks source link

249. Group Shifted String #155

Open jzhangnu opened 6 years ago

jzhangnu commented 6 years ago
var groupStrings = function (str) {
    var res = [], hash = {};

    for (let v of str) {
        let diff = countDiff(v);
        !hash[diff] ? hash[diff] = [v] : hash[diff].push(v)
    }
    for (let i in hash) {
        res.push(hash[i])
    }
    console.log(res)

    function countDiff (str) {
        let key = '0';
        for (let j = 0; j < str.length-1; j++) {
            let temp = str.charCodeAt(j) - str.charCodeAt(j+1);
            temp < 0 ? temp += 26 : null;
            key += temp.toString()
        }
        return key
    }
}