尋找連續字符串問題

1:尋找一串字符中的連續數字串
這個問題我們想算法首先需要有個能夠記錄當前遍歷數字串的容器,然後還需要有個最大的相比。
直接上代碼

#include<iostream>
#include<string>
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<iostream>
#include<string>
#include<vector>
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<stdio.h>
#include<Windows.h>
#include<string.h>
/*
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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章