-
-
Notifications
You must be signed in to change notification settings - Fork 247
[yhkee0404] WEEK 05 solutions #1853
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
+139
−0
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a4e6944
best time to buy and sell stock solution
yhkee0404 b65a3c8
group anagrams solution
yhkee0404 7c9fc48
encode and decode strings solution
yhkee0404 8ea6aba
implement trie prefix tree solution
yhkee0404 37aa074
word break solution
yhkee0404 4350260
word break solution with pruning
yhkee0404 f72c94c
word break solution with pruning 2d
yhkee0404 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,9 @@ | ||
func maxProfit(prices []int) int { | ||
ans := 0 | ||
bought := prices[0] | ||
for i := 1; i != len(prices); i++ { | ||
ans = max(ans, prices[i] - bought) | ||
bought = min(bought, prices[i]) | ||
} | ||
return ans | ||
} |
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,44 @@ | ||
public class Solution { | ||
/* | ||
* @param strs: a list of strings | ||
* @return: encodes a list of strings to a single string. | ||
*/ | ||
public String encode(List<String> strs) { | ||
// write your code here | ||
return strs.parallelStream() | ||
.map(s -> | ||
s.chars() | ||
.parallel() | ||
.mapToObj(c -> new StringBuilder(String.format("%02x", c))) | ||
.collect( | ||
StringBuilder::new, | ||
StringBuilder::append, | ||
(a, b) -> a.append(b) | ||
) | ||
).collect( | ||
StringBuilder::new, | ||
(a, b) -> a.append(b) | ||
.append(' '), | ||
(a, b) -> a.append(b) | ||
).toString(); | ||
} | ||
|
||
/* | ||
* @param str: A string | ||
* @return: decodes a single string to a list of strings | ||
*/ | ||
public List<String> decode(String str) { | ||
// write your code here | ||
final List<String> ans = new ArrayList<>(); | ||
final StringTokenizer st = new StringTokenizer(str); | ||
while (st.hasMoreTokens()) { | ||
final String s = st.nextToken(); | ||
final StringBuilder sb = new StringBuilder(); | ||
for (int i = 0; i < s.length(); i += 2) { | ||
sb.append((char) Integer.parseInt(s.substring(i, i + 2), 16)); | ||
} | ||
ans.add(sb.toString()); | ||
} | ||
return ans; | ||
} | ||
} | ||
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,30 @@ | ||
use itertools::Itertools; | ||
|
||
impl Solution { | ||
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> { | ||
let sorted_strings: Vec<String> = strs | ||
.iter() | ||
.map(|s| { | ||
s.chars() | ||
.sorted() | ||
.collect() | ||
}).collect(); | ||
let inverted_sorted_strings: Vec<usize> = (0..sorted_strings.len()) | ||
.sorted_by_key(|&i| &sorted_strings[i]) | ||
.collect(); | ||
let mut ans: Vec<Vec<String>> = vec![]; | ||
let mut i = 0; | ||
let mut j; | ||
while i != sorted_strings.len() { | ||
let mut u: Vec<String> = vec![]; | ||
j = i; | ||
while j == i || j != inverted_sorted_strings.len() && sorted_strings[inverted_sorted_strings[i]] == sorted_strings[inverted_sorted_strings[j]] { | ||
u.push(strs[inverted_sorted_strings[j]].clone()); | ||
j += 1; | ||
} | ||
ans.push(u); | ||
i = j | ||
} | ||
ans | ||
} | ||
} |
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,40 @@ | ||
class Trie { | ||
|
||
final int n; | ||
final children = <int, Trie>{}; | ||
bool ended = false; | ||
|
||
Trie([this.n = 0]); | ||
|
||
void insert(String word) { | ||
Trie u = this; | ||
for (int rune in word.runes) { | ||
u = u.children | ||
.putIfAbsent(rune, () => Trie(rune)); | ||
} | ||
u.ended = true; | ||
} | ||
|
||
bool search(String word) => _search(word)?.ended ?? false; | ||
|
||
bool startsWith(String prefix) => _search(prefix) != null; | ||
|
||
Trie? _search(String word) { | ||
Trie? u = this; | ||
for (int rune in word.runes) { | ||
u = u!.children[rune]; | ||
if (u == null) { | ||
return null; | ||
} | ||
} | ||
return u; | ||
} | ||
} | ||
|
||
/** | ||
* Your Trie object will be instantiated and called as such: | ||
* Trie obj = Trie(); | ||
* obj.insert(word); | ||
* bool param2 = obj.search(word); | ||
* bool param3 = obj.startsWith(prefix); | ||
*/ |
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,16 @@ | ||
object Solution { | ||
def wordBreak(s: String, wordDict: List[String]): Boolean = { | ||
val dp = Array.fill(s.length + 1)(false) // S(s, wordDict, word) = O(s.length) | ||
dp(0) = true | ||
(0 to s.length - 1).exists { i => | ||
if (! dp(i)) false | ||
else wordDict.exists { word => | ||
val j = i + word.length | ||
if (j <= s.length && ! dp(j) && s.substring(i, j) == word) { | ||
dp(j) = true // T(s, wordDict, word) = O(s.length * wordDict.length * word.length) | ||
} | ||
dp(s.length) | ||
} | ||
} | ||
} | ||
} |
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.
stream으로 푸셨는데 자바에서 stream을 사용하면 속도가 늦어진다고 알고있는데 통과 시간이 어떻게 되었나요?
Uh oh!
There was an error while loading. Please reload this page.
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.
Lintcode에 가입하지 않아서 제출은 못해보고 개인적으로 샘플 테스트만 해봤는데 혹시 가능하시면 비교 부탁드립니다.
다만 Stream을 사용하면 속도가 느려진다는 것은 편견이라고 생각합니다.
특히 ParallelStream을 사용해서 잘 지원되면 더 빠를 수도 있어요. 느린 경우 지원이 빈약한 것이겠죠.
한편 Effective Java에서 사용상의 주의사항은 봤습니다.
그리고 Java API 문서를 다시 보니
Collectors.joining()
도 써보지 않은 것이 후회되네요. 알려 주셔서 감사합니다!