-
-
Notifications
You must be signed in to change notification settings - Fork 195
[byol-han] WEEK 06 solutions #1430
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c5ef509
valid parentheses solution
byol-han 7b47bb7
container with most water solution
byol-han db563ea
longest increasing subsequence solution
byol-han ebe936c
spiral matrix solution
byol-han e08cf3a
design-add-and-search-words-data-structure solution
byol-han File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/** | ||
* https://leetcode.com/problems/container-with-most-water/ | ||
* @param {number[]} height | ||
* @return {number} | ||
*/ | ||
var maxArea = function (height) { | ||
let left = 0; | ||
let right = height.length - 1; | ||
let maxWater = 0; | ||
|
||
while (left < right) { | ||
let width = right - left; // 현재 너비는 두 포인터 사이 거리 | ||
let minHeight = Math.min(height[left], height[right]); // 현재 높이는 두 선 중 더 낮은 값 (물이 넘치지 않기 위해 낮은 선 기준) | ||
let area = width * minHeight; // 현재 구간이 담을 수 있는 물의 양 계산 | ||
|
||
maxWater = Math.max(maxWater, area); // 최대 물 저장량 갱신 | ||
|
||
// 낮은 쪽 포인터를 이동시켜서 더 큰 높이를 찾음 | ||
if (height[left] < height[right]) { | ||
left++; | ||
} else { | ||
right--; | ||
} | ||
} | ||
|
||
return maxWater; | ||
}; |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 일단 그냥 올림. 공부 더 해야함 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// 각 문자 노드를 나타내는 TrieNode 클래스 | ||
class TrieNode { | ||
constructor() { | ||
this.children = {}; // 자식 노드들을 저장하는 객체 (예: { a: TrieNode, b: TrieNode, ... }) | ||
this.isEndOfWord = false; // 단어가 이 노드에서 끝나는지 여부 | ||
} | ||
} | ||
|
||
class WordDictionary { | ||
constructor() { | ||
this.root = new TrieNode(); // 루트 노드 생성 (모든 단어의 시작점) | ||
} | ||
|
||
/** | ||
* 단어를 Trie에 추가 | ||
* @param {string} word | ||
*/ | ||
addWord(word) { | ||
let node = this.root; | ||
for (let char of word) { | ||
// 현재 문자가 자식 노드에 없으면 새 노드 생성 | ||
if (!node.children[char]) { | ||
node.children[char] = new TrieNode(); | ||
} | ||
// 다음 문자로 이동 | ||
node = node.children[char]; | ||
} | ||
// 단어가 끝나는 지점 표시 | ||
node.isEndOfWord = true; | ||
} | ||
|
||
/** | ||
* 단어 검색 (.은 와일드카드로 어떤 문자든 대체 가능) | ||
* @param {string} word | ||
* @returns {boolean} | ||
*/ | ||
search(word) { | ||
/** | ||
* DFS 방식으로 검색을 수행 (백트래킹 포함) | ||
* @param {TrieNode} node - 현재 노드 | ||
* @param {number} i - 현재 탐색 중인 문자 인덱스 | ||
*/ | ||
const dfs = (node, i) => { | ||
// 단어 끝에 도달하면 isEndOfWord 여부 반환 | ||
if (i === word.length) { | ||
return node.isEndOfWord; | ||
} | ||
|
||
const char = word[i]; | ||
|
||
// 현재 문자가 '.'일 경우 모든 자식 노드 탐색 | ||
if (char === ".") { | ||
for (let child of Object.values(node.children)) { | ||
// 하나라도 성공하면 true 반환 | ||
if (dfs(child, i + 1)) return true; | ||
} | ||
// 모든 자식 노드가 실패하면 false 반환 | ||
return false; | ||
} else { | ||
// 해당 문자로 연결된 자식 노드가 없으면 false | ||
if (!node.children[char]) return false; | ||
// 다음 문자로 재귀 호출 | ||
return dfs(node.children[char], i + 1); | ||
} | ||
}; | ||
|
||
// 루트 노드부터 검색 시작 | ||
return dfs(this.root, 0); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* https://leetcode.com/problems/longest-increasing-subsequence/ | ||
* @param {number[]} nums | ||
* @return {number} | ||
*/ | ||
var lengthOfLIS = function (nums) { | ||
if (nums.length === 0) return 0; | ||
|
||
const dp = new Array(nums.length).fill(1); // 최소 길이는 1 (자기 자신만 포함) | ||
|
||
for (let i = 1; i < nums.length; i++) { | ||
// 현재 숫자 이전의 숫자들과 비교 | ||
for (let j = 0; j < i; j++) { | ||
// 증가하는 순서인지 확인 | ||
if (nums[i] > nums[j]) { | ||
// 증가하는 subsequence가 발견되면 길이 갱신 | ||
dp[i] = Math.max(dp[i], dp[j] + 1); | ||
} | ||
} | ||
} | ||
|
||
return Math.max(...dp); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
/** | ||
* https://leetcode.com/problems/spiral-matrix/ | ||
* @param {number[][]} matrix | ||
* @return {number[]} | ||
*/ | ||
var spiralOrder = function (matrix) { | ||
const result = []; | ||
if (matrix.length === 0) return result; | ||
|
||
let top = 0; | ||
let bottom = matrix.length - 1; | ||
let left = 0; | ||
let right = matrix[0].length - 1; | ||
|
||
while (top <= bottom && left <= right) { | ||
// 1. 좌 -> 우 | ||
for (let col = left; col <= right; col++) { | ||
result.push(matrix[top][col]); | ||
} | ||
top++; // 위쪽 경계 한 줄 아래로 이동 | ||
|
||
// 2. 위 -> 아래 | ||
for (let row = top; row <= bottom; row++) { | ||
result.push(matrix[row][right]); | ||
} | ||
right--; // 오른쪽 경계 왼쪽으로 이동 | ||
|
||
// 3. 우 -> 좌 | ||
if (top <= bottom) { | ||
for (let col = right; col >= left; col--) { | ||
result.push(matrix[bottom][col]); | ||
} | ||
bottom--; // 아래쪽 경계 위로 이동 | ||
} | ||
|
||
// 4. 아래 -> 위 | ||
if (left <= right) { | ||
for (let row = bottom; row >= top; row--) { | ||
result.push(matrix[row][left]); | ||
} | ||
left++; // 왼쪽 경계 오른쪽으로 이동 | ||
} | ||
} | ||
|
||
return result; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
function isValid(s) { | ||
const stack = []; | ||
const bracketMap = { | ||
")": "(", | ||
"}": "{", | ||
"]": "[", | ||
}; | ||
Comment on lines
+3
to
+7
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 딕셔너리를 활용한 방법이 굉장히 깔끔하네요! |
||
|
||
for (let char of s) { | ||
if (char === "(" || char === "{" || char === "[") { | ||
stack.push(char); | ||
} else { | ||
// 닫는 괄호가 나왔을 때 스택이 비었거나 짝이 안 맞는 경우 | ||
if (stack.pop() !== bracketMap[char]) { | ||
return false; | ||
} | ||
} | ||
} | ||
|
||
// 모든 괄호가 짝지어졌는지 확인 | ||
return stack.length === 0; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
area변수가 있어 가독성이 좋지만, 생략하고 Math.max(maxWater, width * minHeight) 이렇게 하는 방법도 괜찮을 것 같아요. 주석이 상세히 적혀있어 이해하기 쉬웠습니다.