#import <Foundation/Foundation.h>
int main()
{
NSArray *array = @[@"1234", @"2345", @"3456"];
NSString *string = array[0];
// 找出最短字符串并赋值给string
for (int i = 0; i < arra.count; i++)
{
if (string.length > [array[i] length])
string = array[i];
}
for (int i = (int)string.length; i > 0; i--)
{
int count = 0;
for(int j = 0; j <= string.length - i; j++)
{
//由长到短遍历string的所有子串
NSString *str = [string substringWithRange: NSMakeRange(j, i)];
//遍历所有字符串
for(int n = 0; n < array.count; n++)
{
//若字符串中包含str 则count+1
NSRange range = [array[n] rangeOfString: str];
if(range.location != NSNotFound)
count++;
}
//当count == 字符串数量,即所有字符串都包含str
if(count == array.count)
{
NSLog(@"最长公共字串为%@", str);
break;
}
}
if(count == array.count)
break;
count = 0;
}
return 0;
} |