Longest Match
Input: standard input
Output: standard output
A newly opened detective agency is struggling with their limited intelligence to find out a secret information passing technique among its detectives. Since they are new in this profession, they know well that their messages will easily be trapped and hence modified by other groups. They want to guess the intensions of other groups by checking the changed sections of messages. First they have to get the length of longest match. You are going to help them.
Input
The input file may contain multiple test cases. Each case will contain two successive lines of string. Blank lines and non-letter printable punctuation characters may appear. Each Line of string will be no longer than 1000 characters. Length of each word will be less than 20 characters.
Output
For each case of input, you have to output a line starting with the case number right justified in a field width of two, followed by the longest match as shown in the sample output. In case of at least one blank line for each input output 'Blank!'. Consider the non-letter punctuation characters as white-spaces.
Sample Input
This is a test.test
Hello!
The document provides late-breaking information
late breaking.
Sample Output
1. Length of longest match: 12. Blank!
3. Length of longest match: 2
题意是给你多组单词序列,要输出每2组单词序列lcs,坑点是空行的处理,这里空行指的是只有换行,没有空格,空格要另行处理,需要getline或gets读入,还有非法字符的处理。getline会读掉缓冲区的换行符,而cin则不会读掉,因此当前面用cin读入一个数据时,数据后面的换行符并没有被读掉,此时用getline要注意。getline只是读掉换行,但不是读入,此时字符串的长度还是0。
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#define maxn 1010
#include<cstdio>
using namespace std;
vector<string >ve,se;
int dp[maxn][maxn];
int main(){
string st,str;
int result=0;
while(getline(cin,st)){
int num=st.length();
result++;
getline(cin,str);
int no=str.length();
for(int i=0;i<st.length();i++){
if(st[i]>='a'&&st[i]<='z'||st[i]>='A'&&st[i]<='Z'||st[i]>='0'&&st[i]<='9')
continue;
else{
st[i]=' ';
}
}
for(int i=0;i<str.length();i++){
if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z'||str[i]>='0'&&str[i]<='9')
continue;
else{
str[i]=' ';
}
}
stringstream sd(st);
while(sd>>st){
ve.push_back(st);
}
stringstream sb(str);
while(sb>>str){
se.push_back(str);
}
vector<string>::iterator it=ve.begin();
vector<string>::iterator is=se.begin();
string sm=".";
ve.insert(it,sm);
se.insert(is,sm);
for(int i=1;i<ve.size();i++){
for(int j=1;j<se.size();j++){
dp[i][j]=dp[i-1][j];
if(dp[i][j-1]>dp[i][j]) dp[i][j]=dp[i][j-1];
if(ve[i]==se[j]&&(dp[i-1][j-1]+1)>dp[i][j]){
dp[i][j]=dp[i-1][j-1]+1;
}
}
}
printf("%2d. ",result);
if(!no||!num) cout<<"Blank!"<<endl;
else{
cout<<"Length of longest match: "<<dp[ve.size()-1][se.size()-1]<<endl;
}
ve.clear();
se.clear();
}
return 0;
}