diff --git a/longest-substring-without-repeating-characters/lhc0506.js b/longest-substring-without-repeating-characters/lhc0506.js new file mode 100644 index 000000000..9e28d120e --- /dev/null +++ b/longest-substring-without-repeating-characters/lhc0506.js @@ -0,0 +1,27 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + let maxLength = 0; + const charSet = new Set(); + + let start = 0, end = 0; + + while (end < s.length) { + if (charSet.has(s[end])) { + charSet.delete(s[start]); + start += 1; + continue; + } + + charSet.add(s[end]); + end += 1; + maxLength = Math.max(maxLength, end - start); + } + + return maxLength; +}; + +// 시간복잡도: O(n) +// 공간복잡도: O(n) diff --git a/number-of-islands/lhc0506.js b/number-of-islands/lhc0506.js new file mode 100644 index 000000000..5e5647832 --- /dev/null +++ b/number-of-islands/lhc0506.js @@ -0,0 +1,42 @@ +/** + * @param {character[][]} grid + * @return {number} + */ +var numIslands = function(grid) { + const m = grid.length; + const n = grid[0].length; + const visited = Array.from(new Array(m), () => new Array(n).fill(false)); + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + + let islandCount = 0; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === '1' && !visited[i][j]) { + const queue = [[i, j]]; + visited[i][j] = true; + + while (queue.length) { + const [y, x] = queue.shift(); + + for (const [dy, dx] of directions) { + const newY = y + dy; + const newX = x + dx; + + if (newY >= 0 && newY < m && newX >= 0 && newX < n && grid[newY][newX] === '1' && !visited[newY][newX]) { + visited[newY][newX] = true; + queue.push([newY, newX]); + } + } + } + + islandCount += 1; + } + } + } + + return islandCount; +}; + +// 시간복잡도: O(m * n) +// 공간복잡도: O(m * n) diff --git a/reverse-linked-list/lhc0506.js b/reverse-linked-list/lhc0506.js new file mode 100644 index 000000000..f4577b116 --- /dev/null +++ b/reverse-linked-list/lhc0506.js @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function(head) { + let prevNode = null; + let currentNode = head; + + while(currentNode) { + const nextNode = currentNode.next; + currentNode.next = prevNode; + + prevNode = currentNode; + currentNode = nextNode; + } + + return prevNode; +}; + +// 시간복잡도: O(n) +// 공간복잡도: O(1)