Skip to content

Commit 660413f

Browse files
authored
Merge pull request #1405 from Tessa1217/main
[Tessa1217] Week 05 Solution
2 parents 793112f + 5caf65c commit 660413f

File tree

5 files changed

+204
-0
lines changed

5 files changed

+204
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 주식 가격이 주어지는 prices 배열이 있을 때 최대 주식 이익을 구하시오
3+
* 주식을 산 날짜에는 팔 수 없으며 반드시 산 날짜의 이후 날짜부터(미래부터) 팔 수 있다.
4+
*/
5+
class Solution {
6+
public int maxProfit(int[] prices) {
7+
int maxProfit = 0;
8+
int min = prices[0];
9+
// 굳이 DP 배열 쓰지 않고 계산, 공간 복잡도 낮추기
10+
for (int i = 0; i < prices.length; i++) {
11+
int profit = prices[i] - min;
12+
maxProfit = Math.max(profit, maxProfit);
13+
min = Math.min(prices[i], min);
14+
}
15+
return maxProfit;
16+
}
17+
18+
// public int maxProfit(int[] prices) {
19+
// // 최저 구매
20+
// int[] dp = new int[prices.length];
21+
// dp[0] = prices[0];
22+
// for (int i = 1; i < prices.length; i++) {
23+
// dp[i] = Math.min(prices[i], dp[i - 1]);
24+
// }
25+
// // 최저 구매 배열 기준으로 당일 최대 이익 계산
26+
// int profit = 0;
27+
// for (int i = 1; i < prices.length; i++) {
28+
// profit = Math.max(prices[i] - dp[i - 1], profit);
29+
// }
30+
// return profit;
31+
// }
32+
}
33+
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 문자열에 대한 encode, decode 알고리즘 디자인
3+
* 문자열은 ASCII 256 모두 포함 가능 (문자만 포함한 게 아니므로 특수문자(:, ?) 등도 알고리즘 내에서 고려해야 함
4+
* */
5+
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
public class Solution {
10+
11+
public static String encode(List<String> strs) {
12+
StringBuilder sb = new StringBuilder();
13+
for (String str : strs) {
14+
// : 구분자 앞에 단어의 길이 추가
15+
sb.append(str.length()).append(":").append(str);
16+
}
17+
return sb.toString();
18+
}
19+
20+
public static List<String> decode(String str) {
21+
List<String> words = new ArrayList<>();
22+
int i = 0;
23+
while (i < str.length()) {
24+
// 구분자 기준 인덱스
25+
int colonIdx = str.indexOf(':', i);
26+
// 단어의 길이 인덱스
27+
int length = Integer.parseInt(str.substring(i, colonIdx));
28+
// 단어 시작
29+
int wordStart = colonIdx + 1;
30+
// 단어의 끝
31+
int wordEnd = wordStart + length;
32+
words.add(str.substring(wordStart, wordEnd));
33+
i = wordEnd;
34+
}
35+
return words;
36+
}
37+
38+
}
39+

group-anagrams/Tessa1217.java

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 문자열 배열 strs가 주어질 때 애너그램인 문자들끼리 묶어서 반환하세요.
3+
*/
4+
class Solution {
5+
// 시간복잡도: O(n * L log L)
6+
public List<List<String>> groupAnagrams(String[] strs) {
7+
Map<String, List<String>> anagramMap = new HashMap<>();
8+
for (String str : strs) {
9+
char[] word = str.toCharArray();
10+
Arrays.sort(word);
11+
String sortedCharacter = String.valueOf(word);
12+
if (!anagramMap.containsKey(sortedCharacter)) {
13+
anagramMap.put(sortedCharacter, new ArrayList<>());
14+
}
15+
anagramMap.get(sortedCharacter).add(str);
16+
}
17+
return new ArrayList(anagramMap.values());
18+
}
19+
20+
}
21+
+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* trie는 효율적으로 데이터를 저장하고 키를 통해 문자열 데이터 셋을 검색할 수 있는 트리 구조이다.
3+
* 해당 구조를 활용해 자동완성이나 스펠링 체크를 만들 수 있다.
4+
trie 클래스는 다음과 같이 구현할 수 있다.
5+
Trie() 클래스 생성자
6+
void insert(String word) : trie로 문자열 word를 삽입
7+
boolean search(String word) : 문자열 word가 trie에 있다면 true를 반환
8+
boolean startsWith(String prefix) : prefix가 trie에 있다면 true를 반환
9+
*/
10+
class Trie {
11+
12+
private Node root;
13+
14+
public Trie() {
15+
root = new Node();
16+
}
17+
18+
public void insert(String word) {
19+
Node current = root;
20+
for (char c : word.toCharArray()) {
21+
if (!current.getNodeCharacters().containsKey(c)) {
22+
current.getNodeCharacters().put(c, new Node());
23+
}
24+
current = current.getNodeCharacters().get(c);
25+
}
26+
current.setEnd();
27+
}
28+
29+
public boolean search(String word) {
30+
Node current = root;
31+
for (char c : word.toCharArray()) {
32+
if (!current.getNodeCharacters().containsKey(c)) {
33+
return false;
34+
}
35+
current = current.getNodeCharacters().get(c);
36+
}
37+
return current.getEnd();
38+
}
39+
40+
public boolean startsWith(String prefix) {
41+
Node current = root;
42+
for (char c : prefix.toCharArray()) {
43+
if (!current.getNodeCharacters().containsKey(c)) {
44+
return false;
45+
}
46+
current = current.getNodeCharacters().get(c);
47+
}
48+
return true;
49+
}
50+
51+
static class Node {
52+
53+
// 문자열 끝 여부
54+
private boolean isEnd;
55+
56+
// 키 추출을 위한 맵 구조
57+
private Map<Character, Node> nodeCharacters;
58+
59+
Node() {
60+
nodeCharacters = new HashMap<>();
61+
isEnd = false;
62+
}
63+
64+
public boolean getEnd() {
65+
return this.isEnd;
66+
}
67+
68+
public void setEnd() {
69+
this.isEnd = true;
70+
}
71+
72+
public Map<Character, Node> getNodeCharacters() {
73+
return this.nodeCharacters;
74+
}
75+
76+
}
77+
}
78+
79+
/**
80+
* Your Trie object will be instantiated and called as such:
81+
* Trie obj = new Trie();
82+
* obj.insert(word);
83+
* boolean param_2 = obj.search(word);
84+
* boolean param_3 = obj.startsWith(prefix);
85+
*/
86+

word-break/Tessa1217.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 문자열 s가 주어질 때 wordDict의 단어 문자열로 s가 구성될 수 있는지 여부를 반환하세요.
3+
*/
4+
class Solution {
5+
public boolean wordBreak(String s, List<String> wordDict) {
6+
int n = s.length();
7+
boolean[] dp = new boolean[n + 1];
8+
dp[0] = true;
9+
10+
// contains 최적화를 위해 Set 선언: 시간 복잡도: O(n^2)
11+
Set<String> wordSet = new HashSet<>(wordDict);
12+
13+
for (int i = 1; i <= n; i++) {
14+
for (int j = 0; j < i; j++) {
15+
String word = s.substring(j, i);
16+
if (dp[j] && wordSet.contains(word)) {
17+
dp[i] = true;
18+
break;
19+
}
20+
}
21+
}
22+
return dp[n];
23+
}
24+
}
25+

0 commit comments

Comments
 (0)