Skip to main content

2 posts tagged with "medium"

View All Tags

· 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;
};

· One min read

https://leetcode.com/problems/permutations/

Solution 1

/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function (nums) {
const results = [];

const permutations = (selected) => {
// nums의 모든 숫자가 다 쓰였을 경우
if (selected.length === nums.length) {
results.push(selected);
return;
}

for (let i = 0; i < nums.length; i++) {
// 중복인 숫자는 제외하고 추가
if (!selected.includes(nums[i])) {
permutations([...selected, nums[i]]);
}
}
};

permutations([]);

return results;
};