Last active
March 4, 2019 16:32
-
-
Save leeelton/4491b394ca9591866e2a711e15d7f5ee to your computer and use it in GitHub Desktop.
Daily Coding Challenge 56
This file contains 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
/* | |
Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. | |
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. | |
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. | |
store words in a set | |
loop through string | |
build word | |
if word is in set | |
add word to result | |
word = blank | |
retrun result | |
O(n) time where n is the length of the string | |
O(n) space for storing the temporary word, also O(n) if we have to build the set or O(1) if given it | |
*/ | |
-(NSArray<NSString*> *)splitWords:(NSString *)s setOfWords:(NSArray<NSString*> *)words { | |
NSSet *set = [[NSSet alloc]initWithArray:words]; | |
NSMutableString *word = [[NSMutableString alloc] init]; | |
NSMutableArray *result = [[NSMutableArray alloc] init]; | |
for (int i = 0; i < s.length; ++i) { | |
char c = [s characterAtIndex:i]; | |
[word appendString:@(c)]; | |
if ([set containsObject:word]) { | |
[result addObject:word]; | |
word = @"" | |
} | |
} | |
if (result.count == 0) | |
return nil | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment