@Dima, , , , children Trie, children , , -.
Trie.h:
@interface Trie : NSObject
@property (nonatomic, strong, readonly) NSMutableArray <Trie *>*children;
@property (nonatomic, strong) NSString *key;
- (id)initWithKey:(NSString *)key;
- (void)addWord:(NSString *)word;
- (BOOL)isLeaf;
@end
Trie.m:
@interface Trie ()
@property (nonatomic, strong, readwrite) NSMutableArray <Trie *>*children;
@end
@implementation Trie
- (id)initWithKey:(NSString *)key
{
if (self = [super init]) {
_key = key;
}
return self;
}
- (void)addWord:(NSString *)word
{
if (word.length == 0) {
return;
}
if (!self.children) {
self.children = [NSMutableArray new];
}
NSString *firstCharacter = [word substringToIndex:1];
__block Trie *childToUse = nil;
[self.children enumerateObjectsUsingBlock:^(Trie *child, NSUInteger idx, BOOL *stop) {
if ([child.key isEqualToString:firstCharacter]) {
childToUse = child;
*stop = YES;
}
}];
if (!childToUse) {
childToUse = [[Trie alloc] initWithKey:firstCharacter];
[self.children addObject:childToUse];
}
[childToUse addWord:[word substringFromIndex:1]];
}
- (BOOL)isLeaf
{
return self.children.count == 0;
}
@end