示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
示例 3:
输入:s = "a"
输出:"a"
示例 4:
输入:s = "ac"
输出:"a"
-(NSString *)maxString:(NSString *)str{
if (str.length <= 1) {
return str;
}
NSString *tempJi;
NSString *tempOu;
NSString *resultStr = [str substringToIndex:1];
//i:1循环次数,2关键字索引
for (int i = 0 ; i< str.length; i++) {
//内循环mac次数
int loopCount = i < str.length-1-i ? i : (int)(str.length-1-i);
//奇数
if (loopCount != 0) {
for (int j = 1; j< loopCount+1; j++) {
NSString *leftc = [str substringWithRange:NSMakeRange(i-j, 1)];
NSString *rightc = [str substringWithRange:NSMakeRange(i+j, 1)];
if ([leftc isEqualToString:rightc] ) {
tempJi = [str substringWithRange:NSMakeRange(i-j, 2*j+1)];
}else{
break;
}
}
}
resultStr = tempJi.length > resultStr.length ? tempJi : resultStr;
//偶数 add ddac
loopCount = i < str.length-1-i ? i : (int)(str.length-1-i);
if (loopCount != 0) {
for (int j = 0; j< loopCount+1; j++) {
NSString *leftc = [str substringWithRange:NSMakeRange(i-j, 1)];
NSString *rightc;
if (i+j+1 < str.length) {
rightc = [str substringWithRange:NSMakeRange(i+j+1, 1)];
}
if ([leftc isEqualToString:rightc]) {
tempOu = [str substringWithRange:NSMakeRange(i-j, 2*(j+1))];
}else{
break;
}
}
}
resultStr = tempOu.length > resultStr.length ? tempOu : resultStr;
}
return resultStr;
}
NSLog(@"结果%@",[self maxString:@"caaaac"]);