首页 > 代码库 > 最大公共字符串
最大公共字符串
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
最大公共字符串
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。