好的,所以我正在尝试比较两个字符串,一个是八个字母长,一个可能是 3-8 个字母长,看看较短的字符串是否可以由较长的字母组成。遵循一些算法和技巧,我得到了一些几乎可以工作的东西,但并非在所有情况下都有效。
和被重新排序成字母顺序(例如,将成为haystack
和将成为)。在某些情况下,这是可行的,但如果存在多个字母,则会出现问题。一个这样的坏例子是它认为内部确实存在,显然它不应该存在,因为它有三个 A。needle
tomatoes
aemoostt
toe
eot
aaabrs
aabeirsz
如果有人可以浏览我的方法并发现问题发生的位置,我将非常非常感激。提前致谢。
- (void)viewDidLoad {
[super viewDidLoad];
BOOL doesWordExist = NO;
doesWordExist = [self doesEightLetterWord: @"aabeirsz" containWord: @"aaabrs"];
NSLog(doesWordExist ? @"Does it exist? Yes" : @"Does it exist? No");
}
- (BOOL) doesEightLetterWord: (NSString* )haystack containWord: (NSString *)needle {
for (int i = 0; i < [needle length]; i++) {
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 NO;
} 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);
if ([newNeedle isEqualToString:@""]) {
return YES;
}
}
}
return NO;
}