公共字符串个数

输入过程中getline会认为是一个字符串,所以利用string中的find()函数找到第一次出现空格,并用assign()进行复制计算,分成两个string。

   string s,s1,s2;
    getline(cin,s);
    int len=s.length();
    int k=s.find_first_of(' ',0);
    s1.assign(s,0,k);
    s2.assign(s,k+1,len);//分成两个s1,s2

计算两个字符串的最大公共子串(Longest Common Substring)的长度,字符不区分大小写。

第一种方法,直接进行比较和循环嵌套,由于是不区分大小写,大小写之间的差值是32.

#include <iostream>
#include <string>
using namespace std;
int getCommonStrLength( char *pFirstStr, char *pSecondStr)
{
	
	int i,max;
    char *binF,*endF,*binS,*endS;
    max=0;
    for (binF=pFirstStr;*binF!='\0';binF++)
    {
        endF=binF;
        for (binS=pSecondStr;*binS!='\0';binS++)
        {
            endS=binS;
            i=0;
            while(*endF!='\0' && *endF!='\0'&& (*endF==*endS ||*endF==(*endS+'A'-'a') ||*endS==(*endF+'A'-'a')))
            {
                i++;
                endF++;
                endS++;
            }
            if(max<=i)
                max=i;
        }
	}
	return max;

}


int main()
{
	char s1[100],s2[100];
	cin>>s1;
	cin>>s2;
	int result=getCommonStrLength( s1, s2);
	cout<<result<<endl;
	
	system("pause");
	return 0;
}


第二种方法,形成table进行比较分析table如下所示,只有满足图中的信息才能加1,即在左上角的是不为0的数,才能加1,最后

是数字最大的就是公共字符串的个数。用的是vector矢量。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int getCommonStrLength(string pFirstStr, string pSecondStr)
{
	
	if( (pFirstStr==" ")|| (pSecondStr==" "))
		return 0;
	int m=pFirstStr.size();
	int n=pSecondStr.size();

	vector<vector<int> > table(m+1,vector<int>(n+1));
	int max=0;
	for(int i=0;i<m+1;++i)
		{
		for(int j=0;j<n+1;++j)
		{
			if(i==0||j==0)
				table[i][j]=0;
			else if(pFirstStr[i-1]==pSecondStr[j-1])
			{
				table[i][j]=table[i-1][j-1]+1;
				if(table[i][j]>max)
					max=table[i][j];
			}
			else
				table[i][j]=0;
		}
		}
		return max;
}

int main()
{
	string s,s1,s2;
	getline(cin,s);
	int len=s.length();
	int k=s.find_first_of(' ',0);
	s1.assign(s,0,k);
	s2.assign(s,k+1,len);
	
	int result=getCommonStrLength( s1, s2);
	cout<<result<<endl;
	
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值