我有一个算法来在一组八个字母的单词中找到回文。实际上,它是把长单词中的字母分开,一个接一个地和更短的单词做同样的动作,看看它们是否存在于较长的单词中,就像这样:tower = eortw
two = otw
rot = ort
这里的问题是,如果我在ort
中查找eortw
(或在塔中腐烂),它会找到它,没问题。塔里面有腐烂的东西。但是,otw
不在eortw
内(或两个在塔中),因为r在中间。所以,塔里不会有两个。
有更好的办法吗?我试着用objective-c来实现它,8个字母的单词和常规单词都存储在NSDictionaries
中(以它们的正常和字母顺序的形式)。
我看过很多其他的帖子。stackoverflow上的anagrams,但似乎没有一个能解决这个特殊问题。
以下是我目前掌握的情况:
- (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);
}
}
}
最佳答案
这是一种方法,我可能会采取找出,如果一个有序字包含所有字母的另一个有序字。注意,它找不到真正的anagrams(这只是要求两个有序字符串相同),但这符合我的要求:
+(BOOL) does: (NSString* )longWord contain: (NSString *)shortWord {
NSString *haystack = [longWord copy];
NSString *needle = [shortWord copy];
while([haystack length] > 0 && [needle length] > 0) {
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: [needle substringToIndex:1]];
if ([haystack rangeOfCharacterFromSet:set].location == NSNotFound) {
return NO;
}
haystack = [haystack substringFromIndex: [haystack rangeOfCharacterFromSet: set].location+1];
needle = [needle substringFromIndex: 1];
}
return YES;
}