Skip to main content

4 posts tagged with "stringMatching"

View All Tags

· One min read

https://leetcode.com/problems/rotate-string/

Solution 1

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

let rearrangeS = s;
for (let i = 0; i < s.length; i++) {
rearrangeS = rearrangeS.slice(1) + rearrangeS.slice(0, 1);
if (rearrangeS === goal) {
return true;
}
}
return false;
};

Runtime: 64 ms, faster than 90.15% of JavaScript online submissions for Rotate String.

Memory Usage: 42 MB, less than 66.54% of JavaScript online submissions for Rotate String.

· One min read

https://leetcode.com/problems/most-common-word/

/**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
var mostCommonWord = function (paragraph, banned) {
const onlyLowerCase = paragraph
.toLowerCase()
.split(/[ !?',;.]/)
.filter((val) => val !== '');
const hashTable = {};

onlyLowerCase.forEach((word) => {
if (!banned.includes(word)) {
hashTable[word] = hashTable[word] + 1 || 1;
}
});

const maxCount = Math.max(...Object.values(hashTable).map((value) => value));

return Object.keys(hashTable).find((key) => hashTable[key] === maxCount);
};

Runtime: 75 ms, faster than 90.68% of JavaScript online submissions for Most Common Word.

Memory Usage: 43.9 MB, less than 82.19% of JavaScript online submissions for Most Common Word.

· One min read

https://leetcode.com/problems/repeated-substring-pattern/

/**
* @param {string} s
* @return {boolean}
*/
var repeatedSubstringPattern = function (s) {
// s를 두 번 반복한 후, 첫 글자, 맨 마지막 글자를 제거한 후 그 안에 s가 들어있는지 판별
return s.repeat(2).slice(1, -1).includes(s);
};

Runtime: 106 ms, faster than 61.11% of JavaScript online submissions for Repeated Substring Pattern.

Memory Usage: 45 MB, less than 60.32% of JavaScript online submissions for Repeated Substring Pattern.

· One min read

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/

Solution 1

/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (haystack.length === 0) {
if (needle.length === 0) return 0;
return -1;
}
if (haystack.length !== 0) {
if (needle.length === 0) return 0;
}

let index;
const needleFirstStr = needle[0];

for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needleFirstStr) {
if (haystack.substring(i, i + needle.length) === needle) {
index = i;
break;
} else {
index = -1;
}
} else {
index = -1;
}
}

return index;
};