我有一个算法可以在一组八个字母的单词中找到字谜。实际上,它是将较长单词中的字母按字母顺序排列,对较短的单词一个接一个地执行相同的操作,并查看它们是否存在于较长的单词中,如下所示:
tower = eortw
two = otw
rot = ort
这里的问题是,如果我ort
在里面寻找eortw
(或在塔中腐烂),它会找到它,没问题。腐烂在塔内被发现。但是,otw
不在里面eortw
(或两个在塔中),因为中间有 R。因此,它认为在塔中找不到两个。
有没有更好的方法可以做到这一点?我正在尝试在 Objective-C 中执行此操作,并且八个字母的单词和常规单词都存储在NSDictionaries
(以其正常和按字母顺序排列的形式)中。
我看过其他各种帖子。StackOverflow 上的字谜,但似乎没有一个解决这个特定问题。
这是我到目前为止所拥有的:
- (BOOL) doesEightLetterWord: (NSString* )haystack containWord: (NSString *)needle {
for (int i = 0; i < [needle length] + 1; i++) {
if (!needle) {
NSLog(@"DONE!");
}
NSString *currentCharacter = [needle substringWithRange:NSMakeRange(i, 1)];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: currentCharacter];
NSLog(@"Current character is %@", currentCharacter);
if ([haystack rangeOfCharacterFromSet:set].location == NSNotFound) {
NSLog(@"The letter %@ isn't found in the word %@", currentCharacter, haystack);
return FALSE;
} else {
NSLog(@"The letter %@ is found in the word %@", currentCharacter, haystack);
int currentLocation = [haystack rangeOfCharacterFromSet: set].location;
currentLocation++;
NSString *newHaystack = [haystack substringFromIndex: currentLocation];
NSString *newNeedle = [needle substringFromIndex: i + 1];
NSLog(@"newHaystack is %@", newHaystack);
NSLog(@"newNeedle is %@", newNeedle);
}
}
}