Skip to main content

16 posts tagged with "hashTable"

View All Tags

· One min read

https://leetcode.com/problems/happy-number/

Solution 1

/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function (n) {
let set = new Set();

while (!set.has(n)) {
set.add(n);
let s = n.toString();
n = 0;
for (let i = 0; i < s.length; ++i) {
n += squares[s[i]];
}
if (n === 1) return true;
}

return false;
};

const squares = {
0: 0,
1: 1,
2: 4,
3: 9,
4: 16,
5: 25,
6: 36,
7: 49,
8: 64,
9: 81,
};

· One min read

https://leetcode.com/problems/valid-anagram/

Solution 1

/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false;
}

const hashMapS = {};
const hashMapT = {};

for (let i = 0; i < s.length; i++) {
if (hashMapS[s[i]]) {
hashMapS[s[i]] += 1;
} else {
hashMapS[s[i]] = 1;
}

if (hashMapT[t[i]]) {
hashMapT[t[i]] += 1;
} else {
hashMapT[t[i]] = 1;
}
}

const compareST = Object.entries(hashMapS).map(([key, value]) => {
console.log(value, hashMapT[key]);
console.log(value === hashMapT[key]);
if (value === hashMapT[key]) {
return true;
}
return false;
});

return compareST.every((b) => b);
};

· One min read

https://leetcode.com/problems/word-pattern/

Solution 1

/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function (pattern, s) {
const splitS = s.split(' ');

if (splitS.length !== pattern.length) {
return false;
}

if (new Set(pattern.split('')).size !== new Set(splitS).size) {
return false;
}

const hashMap = {};
for (let i = 0; i < pattern.length; i++) {
if (hashMap[pattern[i]]) {
if (hashMap[pattern[i]] !== splitS[i]) {
return false;
}
} else {
hashMap[pattern[i]] = splitS[i];
}
}

return true;
};

· One min read

https://leetcode.com/problems/first-unique-character-in-a-string/

Solution 1

/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
const hashMap = {};
for (let i = 0; i < s.length; i++) {
if (hashMap[s[i]]) {
hashMap[s[i]] = {
...hashMap[s[i]],
count: hashMap[s[i]].count + 1,
};
} else {
hashMap[s[i]] = {
index: i,
count: 1,
};
}
}

const filteredResult = Object.entries(hashMap)
.map(([key, value]) => {
if (value.count === 1) {
return value.index;
}
})
.filter((value) => value !== false && value !== undefined);

return filteredResult.length === 0 ? -1 : filteredResult[0];
};