對稱子串的最大長度

首先寫一個判斷子串是否對稱的函數

//判斷子串是否對稱
bool  isSymmetrical(char *pbegin, char *pend)  
{
	if(!pbegin||!pend||pbegin>pend)
		return false;
	while(pbegin<pend)
	{
		if(*pbegin!=*pend)
			return false;
		pbegin++;
		pend--;
	}
	return true;
}


最直觀的方法就是把所有子串都找出來,選擇滿足條件的子串長度最大的那個。

很明顯這種方法的時間複雜度會很高

int getLongest(char *pString)
{
	if(!pString)
		return 0;
	int symmeticalLength=1;  //始終保存當前已經找出的最長匹配序列的長度
	char *pFirst=pString;
	int length=strlen(pString);
	while(pFirst<(pString+length-1))
	{
		char *pLast=pFirst+1;
		while(pLast<(pString+length))
		{
			if(isSymmetrical(pFirst,pLast))
			{
				int newLength=pLast-pFirst+1;
				if(newLength>symmeticalLength)
					symmeticalLength=newLength;
			}
			pLast++;
		}
		pFirst++;
	}
	return symmeticalLength;
}

可以對這種方法進行優化

我們先判斷子字符串A是不是對稱的,如果不是對稱的,則左右分別延長一個字符也不是對稱的。

如果A對稱,那麼我們只需要判斷左右一個字符是不是相等。

int getLongest2(char *pString)
{
	if(!pString)
		return 0;
	int symmeticalLength=1;
	char *pChar=pString;
	while(*pChar!='\0')
	{
		//按照奇數位進行判斷,例如aba
		char *pFirst=pChar-1;
		char *pLast=pChar+1;
		while(pFirst>=pString&&*pLast!='\0'&&*pFirst==*pLast)
		{
			pFirst--;
			pLast++;
		}
		int newLength=pLast-pFirst-1;
		if(newLength>symmeticalLength)
			symmeticalLength=newLength;
		//按照偶數爲進行判斷,例如 abba
		pFirst=pChar;
		pLast=pChar+1;
		while(pFirst>=pString&&*pLast!='\0'&&*pFirst==*pLast)
		{
			pFirst--;
			pLast++;

		}
		newLength=pLast-pFirst-1;
		if(newLength>symmeticalLength)
			symmeticalLength=newLength;
	    pChar++;
	}
	return symmeticalLength;
}




發佈了40 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章