回文串:正反读都是一样的字符串,如:abba,aba,
给你一个字符串 s,找到 s 中最长的回文子串。
- (void)test {
NSDictionary *dic = [self searchMaxLengthPalindrome:@"abacdcaba"];
NSLog(@"%@", dic);
}
- (NSDictionary *)searchMaxLengthPalindrome:(NSString *)str {
NSInteger maxlength = 0, leftStart = 0;
for (NSInteger i = 0; i < str.length; i++) {
NSInteger left = i - 1, right = i + 1, length = 1;
char iC = [str characterAtIndex:i];
while (left >= 0 && [str characterAtIndex:left] == iC) {
left--;
length++;
}
while (right < str.length && [str characterAtIndex:right] == iC) {
right++;
length++;
}
while (left >= 0 && right < str.length && [str characterAtIndex:left] == [str characterAtIndex:right]) {
left--;
right++;
length += 2;
}
if (maxlength < length) {
maxlength = length;
leftStart = left;
}
}
return
@{
@"left": @(leftStart + 1),
@"right": @(leftStart + maxlength),
@"lenght": @(maxlength),
@"value": [[str substringToIndex:(leftStart + 1 + maxlength)] substringFromIndex:leftStart + 1]
};
}
输出的结果:
{
left = 0;
lenght = 9;
right = 9;
value = abacdcaba;
}
网友评论