diff --git a/best-time-to-buy-and-sell-stock/dahyeong-yun.java b/best-time-to-buy-and-sell-stock/dahyeong-yun.java new file mode 100644 index 0000000000..837eedb0a4 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/dahyeong-yun.java @@ -0,0 +1,18 @@ +/** + * TC : O(n) + * - 가격 배열 n-1 만큼 순회하므로 O(n) + * SC : O(1) + * - 상수 개의 변수만 사용하므로 O(1) + */ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit = 0; // 안사는 것이 최선인 경우 + int minPrice = prices[0]; // 첫번째 가격으로 사는 경우 + + for(int i=1; i> groupAnagrams(String[] strs) { + Map> answer = new HashMap<>(); + + for(String str : strs) { + char[] c = str.toCharArray(); + Arrays.sort(c); + String key = String.valueOf(c); + answer.computeIfAbsent(key, k -> new ArrayList<>()).add(str); + } + + return new ArrayList<>(answer.values()); + } +} diff --git a/word-break/dahyeong-yun.java b/word-break/dahyeong-yun.java new file mode 100644 index 0000000000..249510d435 --- /dev/null +++ b/word-break/dahyeong-yun.java @@ -0,0 +1,39 @@ +/** + * n: 문자열 s의 길이, m: wordDict 단어 수, k: 단어의 평균 길이 + * - TC: O(n * m * k) -> n개 인덱스 방문 × m개 단어 순회 × k 길이 문자열 비교 + * - SC: O(n) -> 메모이제이션 배열 및 재귀 스택 깊이 O(n) + */ +class Solution { + String s; + int len = 0; + boolean[] imposible; + List wordDict; + + public boolean wordBreak(String s, List wordDict) { + this.s = s; + this.len = s.length(); + this.imposible = new boolean[len]; + this.wordDict = wordDict; + return dfs(0); + } + + public boolean dfs(int index) { + if(index == len) { + return true; + } + + if(imposible[index]) return false; + + for(String word : wordDict) { + int wordLength = word.length(); + if(s.startsWith(word, index)) { + if(len >= index + wordLength) { + if(dfs(index + wordLength)) return true; + } + } + } + + imposible[index] = true; + return false; + } +}