码迷,mamicode.com
首页 > 其他好文 > 详细

最大公共字符串

时间:2015-01-20 17:42:27      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

 

最大公共字符串

标签:

原文地址:http://www.cnblogs.com/loftyspirit/p/4236387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!