昨天去去哪儿笔试,碰到了一个我们一直很熟悉的命令(diff——ubuntu下面),可以比较字符串,即根据最长公共子串问题,如果A中有B中没有的字符输出形式如下(-ch),如果A中没有,B中有可以输出如下形式(+ch).
#include <iostream>
#include <cstring>
#include <vector>
using namespace std; string LCS(string &s1, string &s2)
{
int row = s1.size();
int col = s2.size();
string table[row + ][col + ];
char rowChar[row + ];
char colChar[col + ];
int cnt = ;
rowChar[] = colChar[] = '\0';
for(int i = row - , cnt = ; i >= ; i--, cnt++)
{
rowChar[cnt] = s1[i];
}
for(int i = col - , cnt = ; i >= ; i--, cnt++)
{
colChar[cnt] = s2[i];
}
char ch1, ch2;
string str1, str2;
for(int i = ; i <= row; i++)
{
for(int j = ; j <= col; j++)
{
ch1 = rowChar[i];
ch2 = colChar[j];
if(ch1 == ch2)
table[i][j] = ch1 + table[i - ][j - ];
else
{
str1 = table[i - ][j];
str2 = table[i][j - ];
if(str1.size() == str2.size())
table[i][j] = str1 < str2 ? str2 : str1;
else
table[i][j] = str1.size() < str2.size() ? str2 : str1;
}
}
}
return table[row][col];
}
void showDiff(string &s1, string &s2, string sub, vector<string> &ret)
{
cout << "Sub = " << sub << endl;
int len1 = s1.size();
int len2 = s1.size();
for(int i = , j = ; i < len1; i++)
{
if(s1[i] != sub[j])
{
string str;
str.push_back('-');
str.push_back(s1[i]);
ret.push_back(str);
}
else
j++;
}
for(int i = , j = ; i < len2; i++)
{
if(s2[i] != sub[j])
{
string str;
str.push_back('+');
str.push_back(s2[i]);
ret.push_back(str);
}
else
j++;
}
} int main()
{
string str1, str2;
cin >> str1 >> str2;
string retSub = LCS(str1, str2);
vector<string> ret;
showDiff(str1, str2, retSub, ret);
vector<string>::iterator iter;
for(iter = ret.begin(); iter != ret.end(); iter++)
cout << *iter << endl;
return ;
}