我有一个算法可以在一组八个字母的单词中查找变位词。实际上,它是将较长单词中的字母按字母顺序排序,然后依次对短单词进行相同的操作,并查看它们是否存在于较长单词中,就像这样:
=
=
=
这里的问题是,如果我在 (或tower中)查找,它会找到,没有问题。Rot被发现在tower中。然而,由于中间的R,不在 (或two在tower中)中。因此,它认为two没有出现在tower中。
有更好的方法吗?我正在尝试在Objective-C中完成它,八个字母的单词和常规单词都存储在中(与它们的正常和按字母顺序排序后的形式)。
我已经查看了StackOverflow上关于变位词的各种其他帖子,但似乎没有解决这个特定问题的。
以下是我目前拥有的:
有更好的方法吗?我正在尝试在Objective-C中完成它,八个字母的单词和常规单词都存储在中(与它们的正常和按字母顺序排序后的形式)。
我已经查看了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);
}
}
}