1529 - Coincidence

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 32 MB

Find a longest common subsequence of two strings.

题目输入

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

题目输出

For each case, output k – the length of a longest common subsequence in one line.

输入/输出样例

输入格式

google
goodbye

输出格式

4

C语言解答

#include <stdio.h>
#include <string.h>

#define Max 100

int main ()
{
	char stra[Max+1];
	char strb[Max+1];
	int dp[Max+1][Max+1];
	while(gets(stra))
	{
		gets(strb);
		int lena=strlen(stra);
		int lenb=strlen(strb);
		for(int i=0;i<=lenb;i++)
			dp[0][i]=0;
		for(int i=0;i<=lena;i++)
			dp[i][0]=0;
		for(int i=1;i<=lena;i++)
			for(int j=1;j<=lenb;j++)
			{
				if(stra[i-1]==strb[j-1])
					dp[i][j]=dp[i-1][j-1]+1;
				else
				{
					if(dp[i-1][j]<dp[i][j-1])
						dp[i][j]=dp[i][j-1];
					else
						dp[i][j]=dp[i-1][j];
				}
			}
		//for(int i=0;i<=lena;i++)
		//{
		//	for(int j=0;j<=lenb;j++)
		//		printf("%d ",dp[i][j]);
		//	printf("\n");
		//}
		printf("%d\n",dp[lena][lenb]);
	}
}

C++解答

#include<stdio.h>
#include<string.h>

int a[101][101];

int LCS(const char *s1,const char *s2)
{
	int m=strlen(s1),n=strlen(s2);
	int i,j;
	a[0][0]=0;
	for(i=1;i<=m;++i)
		a[i][0]=0;
	for(i=1;i<=n;++i)
		a[0][i]=0;
	for(i=1;i<=m;++i)
		for(j=1;j<=n;++j)
		{
			if(s1[i-1]==s2[j-1])
				a[i][j]=a[i-1][j-1]+1;
			else if(a[i-1][j]>a[i][j-1])
				a[i][j]=a[i-1][j];
			else
				a[i][j]=a[i][j-1];
		}
	return a[m][n];
}

int main()
{
	char s1[101],s2[101];
	while(scanf("%s%s",s1,s2)!=EOF)
		printf("%d\n",LCS(s1,s2));
	return 0;
}

Java解答

import java.util.Scanner;


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s=new Scanner(System.in);
		String a,b="123";
		//System.out.println(b.charAt(0));
		while(s.hasNext()){
			a=s.next();
			b=s.next();
			int map[][]=new int[101][101];
			for(int i=0;i<101;i++)
				for(int j=0;j<101;j++) map[i][j]=0;
			for(int i=1;i<=a.length();i++)
				for(int j=1;j<=b.length();j++){
					if(a.charAt(i-1)==b.charAt(j-1)) map[i][j]=map[i-1][j-1]+1;
					else
						map[i][j]=Math.max(map[i-1][j],map[i][j-1]);
					
				}
			System.out.println(map[a.length()][b.length()]);
			
		}
		
	}

}