diff --git a/longest-substring-without-repeating-characters/sukyoungshin.ts b/longest-substring-without-repeating-characters/sukyoungshin.ts new file mode 100644 index 000000000..89497c889 --- /dev/null +++ b/longest-substring-without-repeating-characters/sukyoungshin.ts @@ -0,0 +1,43 @@ +// 1번 풀이 +function lengthOfLongestSubstring1(s: string): number { + let seen = new Set(); + let start = 0; + let maxLength = 0; + + for (let end = 0; end < s.length; end++) { + const char = s[end]; + + // 중복된 문자가 나오면 Set에서 제거하면서 start를 앞으로 이동 + while (seen.has(char)) { + seen.delete(s[start]); + start++; + } + + // 중복이 없으면 현재 윈도우 길이 갱신 + seen.add(char); + maxLength = Math.max(maxLength, end - start + 1); + } + + return maxLength; +} + +// 2번 풀이 +function lengthOfLongestSubstring2(s: string): number { + let substring = ""; + let maxLength = 0; + + for (let i = 0; i < s.length; i++) { + const char = s[i]; + + // 중복 문자가 있다면, 그 문자 이후부터 잘라냄 + if (substring.includes(char)) { + const index = substring.indexOf(char); + substring = substring.slice(index + 1); + } + + substring += char; + maxLength = Math.max(maxLength, substring.length); + } + + return maxLength; +} diff --git a/number-of-islands/sukyoungshin.ts b/number-of-islands/sukyoungshin.ts new file mode 100644 index 000000000..8d0f8b447 --- /dev/null +++ b/number-of-islands/sukyoungshin.ts @@ -0,0 +1,30 @@ +function numIslands(grid: string[][]): number { + let count = 0; + + for (let row = 0; row < grid.length; row++) { + for (let col = 0; col < grid[0].length; col++) { + if (grid[row][col] === "1") { + count++; // 새로운 섬 발견! + dfs(row, col); // 연결된 모든 "1"을 0으로 바꾸기 + } + } + } + + function dfs(row: number, col: number) { + // 1. 범위를 벗어나거나 이미 물(0)이면 return + if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length) + return; + if (grid[row][col] === "0") return; + + // 2. 현재 좌표를 0으로 바꾸고 + grid[row][col] = "0"; + + // 3. 상하좌우로 dfs 재귀 호출 + dfs(row - 1, col); // 위 + dfs(row + 1, col); // 아래 + dfs(row, col - 1); // 왼쪽 + dfs(row, col + 1); // 오른쪽 + } + + return count; +} diff --git a/reverse-linked-list/sukyoungshin.ts b/reverse-linked-list/sukyoungshin.ts new file mode 100644 index 000000000..7475ef11c --- /dev/null +++ b/reverse-linked-list/sukyoungshin.ts @@ -0,0 +1,24 @@ +// Definition for singly-linked list. +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; + } +} + +function reverseList(head: ListNode | null): ListNode | null { + let prev: ListNode | null = null; + let current = head; + let next = null; + + while (current !== null) { + const next = current.next; // 1. 다음 노드를 기억해두고 + current.next = prev; // 2. 현재 노드가 이전 노드를 가리키도록 + prev = current; // 3. 이전 노드를 지금 노드로 업데이트 + current = next; // 4. 현재 노드를 다음 노드로 이동 + } + + return prev; +}