-
-
Notifications
You must be signed in to change notification settings - Fork 232
[soobing] WEEK15 Solutions #1659
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
1fa7e4f
feat(soobing): week15 > construct-binary-tree-from-preorder-and-inord…
soobing a000e26
feat(soobing): week15 > longest-palindromic-substring
soobing 0f2bd4b
feat(soobing): week15 > rotate-image
soobing f075676
feat(soobing): week15 > subtree-of-another-tree
soobing 2c6b6f3
feat(soobing): week15 > alien-dictionary
soobing 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,68 @@ | ||
/** | ||
* 문제 설명 | ||
* - 주어진 단어들을 활용하여 알파벳 순서를 찾는 문제 | ||
* | ||
* 아이디어 | ||
* 1) 위상정렬 (👀 다음에 다시풀어보기) - Kahn's Algorithm | ||
* - 어렵다... | ||
*/ | ||
function alienOrder(words: string[]): string { | ||
const graph: Map<string, Set<string>> = new Map(); | ||
const inDegree: Map<string, number> = new Map(); // 간선의 갯수(첫 시작이 무엇인지 판단하기 위함) | ||
|
||
// 단어들에 나오는 모든 문자를 정리 및 초기화 | ||
for (const word of words) { | ||
for (const char of word) { | ||
if (!graph.has(char)) { | ||
graph.set(char, new Set()); | ||
inDegree.set(char, 0); | ||
} | ||
} | ||
} | ||
|
||
// 단어들을 비교해서 알파벳 간의 우선 순서(그래프의 간선) 추출 | ||
for (let i = 0; i < words.length - 1; i++) { | ||
const w1 = words[i]; | ||
const w2 = words[i + 1]; | ||
const minLen = Math.min(w1.length, w2.length); | ||
|
||
let foundDiff = false; | ||
|
||
for (let j = 0; j < minLen; j++) { | ||
const c1 = w1[j]; | ||
const c2 = w2[j]; | ||
if (c1 !== c2) { | ||
if (!graph.get(c1)!.has(c2)) { | ||
graph.get(c1)!.add(c2); | ||
inDegree.set(c2, inDegree.get(c2)! + 1); | ||
} | ||
foundDiff = true; | ||
break; | ||
} | ||
} | ||
|
||
// 사전순이 아닌 경우 빈문자열 리턴(If the order is invalid, return an empty string.) | ||
if (!foundDiff && w1.length > w2.length) return ""; | ||
} | ||
|
||
// BFS 위상정렬 시작 | ||
const queue: string[] = []; | ||
for (const [char, degree] of inDegree.entries()) { | ||
if (degree === 0) queue.push(char); | ||
} | ||
|
||
const result: string[] = []; | ||
while (queue.length > 0) { | ||
const current = queue.shift()!; | ||
result.push(current); | ||
|
||
for (const neighbor of graph.get(current)!) { | ||
inDegree.set(neighbor, inDegree.get(neighbor)! - 1); | ||
if (inDegree.get(neighbor) === 0) { | ||
queue.push(neighbor); | ||
} | ||
} | ||
} | ||
|
||
return result.length === inDegree.size ? result.join("") : ""; | ||
} |
43 changes: 43 additions & 0 deletions
43
construct-binary-tree-from-preorder-and-inorder-traversal/soobing.ts
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,43 @@ | ||
/** | ||
* 문제 설명 | ||
* - preorder(전위순회), inorder(중위순회) 배열을 통해 이진트리를 복원한다 | ||
* | ||
* | ||
* 아이디어 | ||
* 1) preorder 배열의 요소는 루트 노드이다, 이를 기준으로 inorder 배열을 좌우로 나눈다. | ||
* 2) 좌우로 나눈 inorder 배열의 길이를 통해 preorder 배열의 좌우 서브트리를 구한다. | ||
* 3) 이를 재귀적으로 반복한다. | ||
*/ | ||
|
||
class TreeNode { | ||
val: number; | ||
left: TreeNode | null; | ||
right: TreeNode | null; | ||
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { | ||
this.val = val === undefined ? 0 : val; | ||
this.left = left === undefined ? null : left; | ||
this.right = right === undefined ? null : right; | ||
} | ||
} | ||
|
||
function buildTree(preorder: number[], inorder: number[]): TreeNode | null { | ||
if (preorder.length === 0 || inorder.length === 0) return null; | ||
|
||
const inorderIndexMap = new Map<number, number>(); | ||
inorder.forEach((value, index) => inorderIndexMap.set(value, index)); | ||
|
||
let preorderIndex = 0; | ||
const helper = (left: number, right: number): TreeNode | null => { | ||
if (left > right) return null; | ||
const rootValue = preorder[preorderIndex++]; | ||
const root = new TreeNode(rootValue); | ||
const index = inorderIndexMap.get(rootValue)!; | ||
|
||
root.left = helper(left, index - 1); | ||
root.right = helper(index + 1, right); | ||
|
||
return root; | ||
}; | ||
|
||
return helper(0, inorder.length - 1); | ||
} |
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,31 @@ | ||
/** | ||
* 문제 설명 | ||
* - 주어진 문자열에서 가장긴 palindromic substring을 찾는 문제 | ||
* | ||
* 아이디어 | ||
* 1) palindrom을 찾는 법(중심 확장법) + 홀수ver, 짝수ver 두 가지 경우를 모두 확인 | ||
* - two pointer 기법을 이용하여 확장하면서 가장 긴 palindromic substring을 찾는다. | ||
*/ | ||
function longestPalindrome(s: string): string { | ||
let maxLength = 0; | ||
let start = 0; | ||
|
||
const expand = (l: number, r: number) => { | ||
while (l >= 0 && r < s.length && s[l] === s[r]) { | ||
const currentLength = r - l + 1; | ||
if (currentLength > maxLength) { | ||
maxLength = currentLength; | ||
start = l; | ||
} | ||
l--; | ||
r++; | ||
} | ||
}; | ||
|
||
for (let i = 0; i < s.length; i++) { | ||
expand(i, i); | ||
expand(i, i + 1); | ||
} | ||
|
||
return s.slice(start, start + maxLength); | ||
} |
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,25 @@ | ||
/** | ||
* 문제 설명 | ||
* - 2차원 배열을 90도 in-place로 회전하기 | ||
* | ||
* 아이디어 | ||
* 1) 대각선 이동 + 좌우 이동 | ||
* | ||
*/ | ||
/** | ||
Do not return anything, modify matrix in-place instead. | ||
*/ | ||
function rotate(matrix: number[][]): void { | ||
const n = matrix.length; | ||
for (let i = 0; i < n; i++) { | ||
for (let j = i + 1; j < n; j++) { | ||
const temp = matrix[i][j]; | ||
matrix[i][j] = matrix[j][i]; | ||
matrix[j][i] = temp; | ||
} | ||
} | ||
|
||
for (let i = 0; i < n; i++) { | ||
matrix[i].reverse(); | ||
} | ||
} |
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,33 @@ | ||
/** | ||
* 문제 설명 | ||
* - 두 개의 이진트리 중, subTree가 존재하는지 확인하는 문제 | ||
* | ||
* 아이디어 | ||
* 1) DFS + isSameTree 체크 | ||
*/ | ||
class TreeNode { | ||
val: number; | ||
left: TreeNode | null; | ||
right: TreeNode | null; | ||
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { | ||
this.val = val === undefined ? 0 : val; | ||
this.left = left === undefined ? null : left; | ||
this.right = right === undefined ? null : right; | ||
} | ||
} | ||
|
||
function isSameTree(tree1: TreeNode | null, tree2: TreeNode | null) { | ||
if ((tree1 && !tree2) || (!tree1 && tree2)) return false; | ||
if (tree1 === null && tree2 === null) return true; | ||
if (tree1?.val !== tree2?.val) return false; | ||
return ( | ||
isSameTree(tree1?.left ?? null, tree2?.left ?? null) && | ||
isSameTree(tree1?.right ?? null, tree2?.right ?? null) | ||
); | ||
} | ||
|
||
function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean { | ||
if (!root) return false; | ||
if (isSameTree(root, subRoot)) return true; | ||
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); | ||
} |
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.
행 열 바꿔준 다음 아예 행 자체를 reverse 하셨네요. 양끝 포인트들을 swap 하는 방식으로 행 뒤집기를 했었는데 간결하게 구현된 걸 보고 배우고 갑니다.