【LeetCode】5.最长的回文子串

暴力解法

思路

1、做一个子函数,用于检测输入的字符串是否是回文串
2、使用双指针,头指针从字符串开始处遍历,尾指针每次均从结尾处开始,检查头尾指针之间的字符串是否是回文串,若是,且长度大于之前的长度,则更新,否则进行下次检查,注意,大循环的结束条件可以随着找到回文子串的长度而更新。

代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>   // for malloc(), free()

#define YES 1
#define NO 	0

int IsPalindrome(char *strIn,int strLength)
{
	for (int i = 0; i < strLength/2; i++) {
		if (strIn[i] != strIn[strLength - 1 - i]) {
			return NO;
		}
	}
	return YES;
}

char * longestPalindrome(char * s)
{
	int strLength = strlen(s);
	if (strLength < 2) {
		return s;
	}

	char tmpLongestPald[1001] = {0};
    tmpLongestPald[0] = s[0];
	int maxLength = 1;
	int endIndex;
	for (int i = 0; i < strLength - maxLength; i++) {
		endIndex = strLength - 1;
		while (endIndex - i+1 > maxLength) {
			if (IsPalindrome(s+i,endIndex-i+1)==YES) {
				if (endIndex - i + 1>maxLength) {
					maxLength = endIndex - i + 1;
					memcpy(tmpLongestPald, s + i, maxLength);
				}
				break;
			} else {
				endIndex--;
			}	
		}	
	}
    char* strRet;
    strRet = (char*)malloc(maxLength+1);
    strcpy(strRet,tmpLongestPald);
	return strRet;
}

优化

思路

1、从字符串头开始遍历
2、找到最小子串后,依次向外扩展
3、最小子串有两种形式 bb 或者 aba
4、根据找到的最大长度选择是否提前结束循环

代码

char * longestPalindrome(char * s)
{
	int strLength = strlen(s);
	if (strLength < 2) {
		return s;
	}

	char tmpLongestPald[1001] = {0};
    tmpLongestPald[0] = s[0];
	int maxLength = 1;
	int sideSize = 0;
	for (int i = 0; i < strLength - maxLength/2; i++) {
		sideSize = 0;
		while ((i-sideSize >= 0) && (i + sideSize + 1 < strLength))
		{
			if (s[i-sideSize] == s[i+sideSize+1]) {
				sideSize++;
			} else {
				break;
			}
		}
		if (maxLength < 2 * sideSize) {
			maxLength = 2 * sideSize;
			memcpy(tmpLongestPald, s+i-sideSize+1, maxLength);
		}
		sideSize = 1;
		while ((i-sideSize >= 0) && (i + sideSize  < strLength))
		{
			if (s[i-sideSize] == s[i+sideSize]) {
				sideSize++;
			} else {
				break;
			}
		}
		if (maxLength < 2 * sideSize - 1 ) {
			maxLength = 2 * sideSize - 1;
			memcpy(tmpLongestPald, s+i-sideSize+1, maxLength);
		}
	}

	char* strRet;
	strRet = (char*)malloc(maxLength+1);
	strcpy(strRet,tmpLongestPald);
	return strRet;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值