最大公共字串

寫在前面:小生純業餘選手,開此博僅僅是爲了積累,純當筆記來用。如有看官光臨小生博客,請不要相信我的代碼就是正確的。如果您發現了錯誤也懇請耽誤您一點時間,請您在下面指出來,不勝感激!


計算兩個字符串的最大公共子串,忽略字符串大小寫,由於OJ編譯器要求,這裏變量全部定義在開頭。


#include "stdafx.h"
#include<iostream>
#include <string.h>
using namespace std;

int getCommonStrLength(char * ppFirstStr, char * ppSecondStr)
{
	int i = 0;
	int j = 0;
	int len = 0;
	int maxlen = 0;
	int p = 0;

	if (ppFirstStr == NULL || ppSecondStr == NULL)
	{
		return 0;
	}
	char *pFirstStr =  strlwr(ppFirstStr);
	char *pSecondStr = strlwr(ppSecondStr);

	while (pFirstStr[i] != '\0')
	{
		p = i;
		while (pSecondStr[j] != '\0' && pSecondStr[j] != pFirstStr[p])
		{
			j++;
		}
		if (pSecondStr[j] == '\0')
		{
			j = 0;
			i++;
		}else{
			while(pFirstStr[p] != '\0' && pSecondStr[j] != '\0' && pFirstStr[p] == pSecondStr[j])
			{
				len++;
				p++;
				j++;
			}
			if (maxlen < len)
			{
				maxlen = len;
			}
			j = 0;
			i++;
			len = 0;
		}
	}
	return maxlen;
}

int _tmain(int argc, _TCHAR* argv[])
{
	/*
	char *pFirstStr = "asdfas";
	char *pSecondStr = "werasdfaswer";
	*/
	char *pFirstStr = new char[256];
	char *pSecondStr = new char[256];
	cin>>pFirstStr>>pSecondStr;
	cout<<getCommonStrLength(pFirstStr,pSecondStr);
	return 0;
}


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