一、Description(3302)
Given a string s of length n, a subsequence of it, is defined as another string s' = su1su2...sum where 1 ≤ u1 < u2 < ... < um ≤ n and si is the ith character of s. Your task is to write a program that, given two strings s1 and s2, checks whether either s2 or its reverse is a subsequence of s1 or not.
Input
The first line of input contains an integer T, which is the number of test cases. Each of the next T lines contains two non-empty strings s1 and s2 (with length at most 100) consisted of only alpha-numeric characters and separated from each other by a single space.
Output
For each test case, your program must output "YES", in a single line, if either s2 or its reverse is a subsequence of s1. Otherwise your program should write "NO".
一、Description(1936)
Given two strings s and t, you have to decide whether s is a subsequence of t, i.e. if you can remove characters from t such that the concatenation of the remaining characters is s.
Input
Output
二、题解
这两道题目都是求LCS问题,只是求解的形式有所不同。求的不是LCS而是判断是否为子序列,其中3302还求逆序列是否为子序列。但不管怎么变,只要记住DP求 LCS算法,题目就很容易求解。
三、java代码
import java.util.Scanner;
public class Main {
public static int LCS(String x,String y){
int [][] z=new int [x.length()+1][y.length()+1];
int i,j;
for( i=0;i<=x.length();i++)
z[i][0]=0;
for( j=0;j<=y.length();j++)
z[0][j]=0;
for(i=1;i<=x.length();i++){
for( j=1;j<=y.length();j++){
if(x.charAt(i-1)==y.charAt(j-1)){
z[i][j]= z[i-1][j-1]+1;
}
else
z[i][j]=z[i-1][j] > z[i][j-1] ?z[i-1][j]:z[i][j-1];
}
}
return z[x.length()][y.length()];
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String s,s1;
int n,i;
n=cin.nextInt();
for(i=0;i<n;i++){
s=cin.next();
s1=cin.next();
if( LCS(s,s1)==s1.length() || LCS(s,new StringBuffer(s1).reverse().toString())==s1.length()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}