Skip to content

[soobing] WEEK05 Solutions #1843

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions best-time-to-buy-and-sell-stock/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* 문제 유형
* - Array
*
* 문제 설명
* - 주식을 가장 싸게 사서 비싸게 팔수 있는 경우 찾기
*
* 아이디어
* 1) 최소값을 찾고 그 이후의 값 중 최대값을 찾는다.
*
*/
function maxProfit(prices: number[]): number {
let min = prices[0];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minPrice 처럼 의미가 분명한 변수명을 사용하면 좋을 것 같습니다.

let maxProfit = 0;

for (let i = 1; i < prices.length; i++) {
min = Math.min(min, prices[i]);
maxProfit = Math.max(prices[i] - min, maxProfit);
}
return maxProfit;
}
42 changes: 42 additions & 0 deletions encode-and-decode-strings/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* 문제 유형
* - String
*
* 문제 설명
* - 문자열 인코딩과 디코딩
*
* 아이디어
* 1) "길이 + # + 문자열" 형태로 인코딩
*
*/
class Solution {
/**
* @param {string[]} strs
* @returns {string}
*/
encode(strs) {
return strs.map((str) => `${str.length}#${str}`).join("");
}

/**
* @param {string} str
* @returns {string[]}
*/
decode(str) {
const result = [];
let tempStr = str;
while (tempStr.length) {
let i = 0;

while (tempStr[i] !== "#") {
i++;
}

const length = Number(tempStr.slice(0, i));
const currentStr = tempStr.slice(i + 1, i + 1 + length);
result.push(currentStr);
tempStr = tempStr.slice(length + i + 1);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slice로 원본을 잘라내면 불필요한 문자열 복사가 반복될 수 있으니 포인터를 만들어서 전진하는 방식도 고려해보면 좋을 것 같아요

}
return result;
}
}
20 changes: 20 additions & 0 deletions group-anagrams/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* 문제 유형
* - String
*
* 문제 설명
* - 애너그램 그룹화
*
* 아이디어
* 1) 각 문자열을 정렬하여 키로 사용하고 그 키에 해당하는 문자열 배열을 만들어 리턴
*
*/
function groupAnagrams(strs: string[]): string[][] {
const map = new Map<string, string[]>();

for (let i = 0; i < strs.length; i++) {
const key = strs[i].split("").sort().join("");
map.set(key, [...(map.get(key) ?? []), strs[i]]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

map.set()은 매번 새 배열을 만들어야하니 꺼내서 push 하는 방식은 어떤가요?

}
return [...map.values()];
}
67 changes: 67 additions & 0 deletions implement-trie-prefix-tree/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* 문제 유형
* - Trie 구현 (문자열 검색)
*
* 문제 설명
* - 문자열 검색/추천/자동완성에서 자주 사용하는 자료구조 Trie 구현
*
* 아이디어
* 1) 문자열의 각 문자를 TrieNode 클래스의 인스턴스로 표현s
*
*/
class TrieNode {
children: Map<string, TrieNode>;
isEnd: boolean;

constructor() {
this.children = new Map();
this.isEnd = false;
}
}

class Trie {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}

insert(word: string): void {
let node = this.root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.isEnd = true;
}

// isEnd 까지 확인이 필요
search(word: string): boolean {
const node = this._findNode(word);
return node !== null && node.isEnd;
}

// isEnd까지 확인 필요 없고 존재 여부만 확인 필요
startsWith(prefix: string): boolean {
return this._findNode(prefix) !== null;
}

private _findNode(word: string): TrieNode | null {
let node = this.root;
for (const char of word) {
if (!node.children.get(char)) return null;
node = node.children.get(char)!;
}

return node;
}
}

/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/