首页 > 代码库 > 最大公共字符串

最大公共字符串

Code:

 1 // 找出两个字符串中的最大公共子字符串 2 // 如"nbitheimanb"和"itheia"的最大公共子串是:"ithei" 3  4 #import <Foundation/Foundation.h> 5  6 int main(int argc, const char * argv[]) { 7     @autoreleasepool { 8         NSString* str1 = @"nbitheimanb"; 9         NSString* str2 = @"ithei";10         11         NSRange maxSubStringRange = NSMakeRange(0, 0);12         for (NSUInteger location = 0; location < [str2 length]; ++location) {13             for (NSUInteger length = [str2 length] - location; length > 0; --length) {14                 NSRange subStringRange = {.location = location, .length = length};15                 NSString* subString = [str2 substringWithRange:subStringRange];16                 if ([str1 rangeOfString:subString].location != NSNotFound) {17                     if (subStringRange.length >= maxSubStringRange.length) {18                         maxSubStringRange = subStringRange;19                     }20                 }21             }22         }23 24         NSString* greatestCommonString = [str2 substringWithRange:maxSubStringRange];25         NSLog(@"Greatest common string = %@", greatestCommonString);26     }27     return 0;28 }

Output:

1 Greatest common string = ithei

 

最大公共字符串