Skip to content
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

[donghyeon95] Week5 #881

Merged
merged 7 commits into from
Jan 12, 2025
Merged
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
24 changes: 24 additions & 0 deletions best-time-to-buy-and-sell-stock/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
int maxProfit = 0;
int buyStock = prices[0];

// 한번 돌면서 나보다 작은 것이 나올 때까지 이익을 본다


for (int price: prices) {
// 나보다 작은 게 나오면 MAX 이익을 갱신하고 거기부서 다시 시작한다.
if (price < buyStock) {
result = Math.max(result, maxProfit);
maxProfit = 0;
buyStock = price;
} else {
maxProfit = Math.max(price - buyStock, maxProfit);
}
}

return Math.max(result, maxProfit);
}
}

57 changes: 57 additions & 0 deletions encode-and-decode-strings/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
String cDel = "&";
String sDel = ";";

// Encodes a list of strings to a single string
public String encode(List<String> strs) {
if (strs.isEmpty()) return null;

StringBuilder result = new StringBuilder();
for (int i =0; i<strs.size(); i++) {
String str = strs.get(i);
StringBuilder temp = new StringBuilder();
for (char c : str.toCharArray()) {
temp.append((int) c).append(cDel);
}

result.append(temp);
if (i != strs.size()-1) result.append(sDel);
}
return result.toString();
}

// Decodes a single string to a list of strings
public List<String> decode(String str) {
if (str==null)
return new ArrayList<>();

List<String> result = new ArrayList<>();
String[] strs = str.split(sDel, -1);
for (String s : strs) {
if (s.isEmpty()) {
result.add("");
continue;
}
String[] chars = s.split(cDel);
String decoded = Arrays.stream(chars)
.filter(sr -> !sr.isEmpty())
.mapToInt(Integer::parseInt)
.mapToObj(ascii -> (char) ascii)
.map(String::valueOf)
.collect(Collectors.joining());
result.add(decoded);
}
return result;
}
}


28 changes: 28 additions & 0 deletions group-anagrams/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// 문자열 정렬을 해서 같은 애들 모음을 주면 되지 않을까??
// 이럴 경우 정렬에 많은 시간을 소모

HashMap<String, List<String>> hm = new HashMap<>();
for (String str: strs) {
String arrangedStr = rearangeStr(str);
hm.putIfAbsent(arrangedStr, new ArrayList<>());
hm.get(arrangedStr).add(str);
}

return hm.values().stream().toList();
}

public String rearangeStr (String str) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
public String rearangeStr (String str) {
public String reArrangeStr (String str) {

FYI: 오타가 있는 것 같습니다

char[] chars = str.toCharArray();
Arrays.sort(chars);

return new String(chars);
}
}

29 changes: 29 additions & 0 deletions implement-trie-prefix-tree/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.HashMap;

class Trie {
Copy link
Contributor

Choose a reason for hiding this comment

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

트라이 자료구조는 트리의 일종인데 노드를 구현하지 않으신 것 같습니다. 노드를 이용해서 구현해보시는 걸 추천드립니다.

HashMap<String, Boolean> trie;
public Trie() {
trie = new HashMap<>();
}

public void insert(String word) {
StringBuilder sb = new StringBuilder();
for (char c: word.toCharArray()) {
sb.append(c);
trie.putIfAbsent(sb.toString(), false);
}
trie.put(sb.toString(), true);
}

public boolean search(String word) {
return trie.getOrDefault(word, false);
}

public boolean startsWith(String prefix) {
return trie.containsKey(prefix);
}
}




41 changes: 41 additions & 0 deletions word-break/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Solution {
Copy link
Contributor

Choose a reason for hiding this comment

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

사실 이 문제는 implement-trie-prefix-tree에서 구현한 트라이 자료구조와 연관이 있는 문제여서, 트라이를 사용해서 풀어보시면 도움이 되실 것 같습니다.

public boolean wordBreak(String s, List<String> wordDict) {
return dfs(s, wordDict, new HashSet<>());
}

private boolean dfs(String s, List<String> wordDict, Set<String> dp) {
// 종료 조건: 문자열이 비어 있으면 성공
if (s.isEmpty()) return true;

// 중복 탐색 방지
if (dp.contains(s)) return false;

for (String word : wordDict) {
if (s.startsWith(word)) {
// 단어를 제거하고 재귀 호출
if (dfs(s.substring(word.length()), wordDict, dp)) {
return true;
}
}
}

// 단어를 제거하지 않고 넘어가는 경우도 탐색
dp.add(s); // 탐색이 실패한 상태 저장
return false;
}
}



Loading