寻找连续字符串问题

1:寻找一串字符中的连续数字串
这个问题我们想算法首先需要有个能够记录当前遍历数字串的容器,然后还需要有个最大的相比。
直接上代码

#include
#include
using namespace std;
//寻找连续最长的数字串
int main()
{
     
	string str, res, cur;
	cin>>str;
	for (size_t i = 0; i <= str.length(); ++i)
	{
     
		if (str[i] >= '0'&&str[i] <= '9')
		{
     
			cur += str[i];
		}
		else
		{
     
			if (res.size() < cur.size())
				res = cur;
				cur.clear();
		}
	}
	cout << res;
	system("pause");
	return 0;
}

2:两字符串最大公共子串。
C++实现

#define _CRT_SECURE_NO_WARNINGS 

#include
#include
#include
using namespace std;
//动态规划字符串匹配问题
void getCommonStrLength(string &str1, string &str2)
{
     
	int len1 = str1.size();
	int len2 = str2.size();
	int max = 0;
	//所有值初始化为0
	vector<vector<int>>  dp(len1, vector<int>(len2, 0));
	//计算dp
	for (int i = 0; i < len1; i++)
	{
     
		for (int j = 0; j < len2; j++)
		{
     
			//如果当前结尾的字符相等,则在dp[i-1][j-1]的基础上加1
			if ((str1[i] == str2[j]))
			{
     
				if (i >= 1 && j >= 1)
					dp[i][j] = dp[i - 1][j - 1] + 1;
				else
					//dp[i][0] or dp[0][j]
					dp[i][j] = 1;
			}
			//更新最大值
			if (dp[i][j] > max)
				max = dp[i][j];
		}
	}
	cout << max << endl;
}
int main()
{
     
	string str1,str2;
	cin >> str1>>str2;
	getCommonStrLength(str1, str2);
	system("pause");
	return 0;
}


C语言实现

#define _CRT_SECURE_NO_WARNINGS 
#include
#include
#include
/*
int f(int i, int j, int(*a)[4])
{
	int f1, f2, tmp = 0, k;
	if (i == 0 || j == 0)
		return a[0][0];
	if (j == i)
	{
		for (k = 0; k <= i; k++)
			tmp += a[k][k];
		return tmp;
	}
	f1 = f(i - 1, j, a);
	f2 = f(i - 1, j - 1, a);
	if (f1 < f2)
		return f2 + a[i][j];
	else
		return f1 + a[i][j];
}

int main()
{

	system("pause");
	return 0;
}
*/
//拿短的去匹配长的
/*
void printcom(char* arr1,char*arr2)
{
	int i = 0;
	int j = 0;
	int temp = 0;
	int temp1 = 0;
	size_t length1 = strlen(arr1);
	size_t length2 = strlen(arr2);
	for (i = 0; i < length1; ++i)
	{
		for (j = 0; j < length2; ++j)
		{
			if (arr2[j] == arr1[i])
			{
				j++;
				i++;
				temp++;
			}
//判断连续与否
		}

	}
}
*/
void printcom(char* arr1, char*arr2)
{
     
	size_t length1 = strlen(arr1);
	size_t length2 = strlen(arr2);
	int temp = 0;
	int** p = (int**)malloc(length1*sizeof(int));
	for (int k = 0; k < length1; ++k)
		p[k] = (int*)malloc(sizeof(int)*length2);
	for (int i = 0; i < length1; ++i)
	{
     
		for (int j = 0; j < length2; ++j)
		{
     
			p[i][j] = 0;
			if (arr1[i] == arr2[j])
			{
     
				p[i][j] = 1;
				if (i > 0 && j > 0)
				{
     
					p[i][j] += p[i - 1][j - 1];
				}
				
			}
			if (p[i][j] > temp)
			{
     
				temp = p[i][j];
			}
		}
	}
	printf("%d", temp);
}
int main()
{
     
	char arr1[100];
	char arr2[100];
	scanf("%s", arr1);
	scanf("%s", arr2);
	printcom(arr1, arr2);

	system("pause");
	return 0;
}
//char** q = (char**)malloc(length1*length2);

你可能感兴趣的:(C++,c++,字符串,算法)