1. 示例 1
    2. 输入:s = "babad"
    3. 输出:"bab"
    4. 解释:"aba" 同样是符合题意的答案。
    5. 示例 2
    6. 输入:s = "cbbd"
    7. 输出:"bb"
    8. 示例 3
    9. 输入:s = "a"
    10. 输出:"a"
    11. 示例 4
    12. 输入:s = "ac"
    13. 输出:"a"
    1. -(NSString *)maxString:(NSString *)str{
    2. if (str.length <= 1) {
    3. return str;
    4. }
    5. NSString *tempJi;
    6. NSString *tempOu;
    7. NSString *resultStr = [str substringToIndex:1];
    8. //i:1循环次数,2关键字索引
    9. for (int i = 0 ; i< str.length; i++) {
    10. //内循环mac次数
    11. int loopCount = i < str.length-1-i ? i : (int)(str.length-1-i);
    12. //奇数
    13. if (loopCount != 0) {
    14. for (int j = 1; j< loopCount+1; j++) {
    15. NSString *leftc = [str substringWithRange:NSMakeRange(i-j, 1)];
    16. NSString *rightc = [str substringWithRange:NSMakeRange(i+j, 1)];
    17. if ([leftc isEqualToString:rightc] ) {
    18. tempJi = [str substringWithRange:NSMakeRange(i-j, 2*j+1)];
    19. }else{
    20. break;
    21. }
    22. }
    23. }
    24. resultStr = tempJi.length > resultStr.length ? tempJi : resultStr;
    25. //偶数 add ddac
    26. loopCount = i < str.length-1-i ? i : (int)(str.length-1-i);
    27. if (loopCount != 0) {
    28. for (int j = 0; j< loopCount+1; j++) {
    29. NSString *leftc = [str substringWithRange:NSMakeRange(i-j, 1)];
    30. NSString *rightc;
    31. if (i+j+1 < str.length) {
    32. rightc = [str substringWithRange:NSMakeRange(i+j+1, 1)];
    33. }
    34. if ([leftc isEqualToString:rightc]) {
    35. tempOu = [str substringWithRange:NSMakeRange(i-j, 2*(j+1))];
    36. }else{
    37. break;
    38. }
    39. }
    40. }
    41. resultStr = tempOu.length > resultStr.length ? tempOu : resultStr;
    42. }
    43. return resultStr;
    44. }
    45. NSLog(@"结果%@",[self maxString:@"caaaac"]);