您的位置:首页 > 其它

输入两个字符串,比如abdcc和abc,输出第二个字符串在第一个字符串中的连接次序

2012-05-09 19:34 627 查看
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
typedef vector<int> vInt;
typedef vInt::iterator itInt;
typedef vector<vInt *> pVint;
typedef vector<vInt> vvInt;
//输入两个字符串,比如abdcc和abc,输出第二个字符串在第一个字符串中的连接次序
//示例的结果应为:125,126,145,146

//计算str2每个字母在str中出现的位置
pVint seq(char *str1,char *str2)
{
int len1=strlen(str1);
int len2=strlen(str2);
//使用一个vector <vector<int> *>存储返回结果
pVint vres;
for (int i=0; i<len2; i++)
{
//存储str2中每个字母在str1中出现的位置
vInt *pTmp=new vInt;
for (int j=0;j<len1; j++)
{
if(str2[i]==str1[j]){
pTmp->push_back(j+1);
}
}
vres.push_back(pTmp);
}
return vres;
}

//计算两个序列的笛卡尔积,第一个序列是vector <vector<int>>
//第二个是vector<int>,返回最终结果为笛卡尔积结果vector <vector<int>>
//如:{{1,2},{3,4}}*{5,6}={{1,2,5},{1,2,6},{3,4,5},{3,4,6}}
vvInt multi(vvInt v1, vInt v2)
{
int len1=v1.size();
int len2=v2.size();
pVint res;
for (int i=0;i<len1;i++)
{
for (int j=0; j<len2; j++)
{
//注意这两层for循环次序
vInt *tmp=new vInt;
for (int m=0; m<v1[i].size(); m++)
tmp->push_back(v1[i][m]);
tmp->push_back(v2[j]);
res.push_back(tmp);
}
}
vvInt fin;
for (int j=0;j<res.size();j++)
fin.push_back(*res[j]);
return fin;
}

int main()
{
char str1[]="abdbcc";
char str2[]="abc";
pVint pRes=seq(str1,str2);

//构造第一个vector <vector<int>>来作为基数((1))
pVint tmp;
for (int i=0;i<(*pRes[0]).size();i++){
vInt *tmp1=new vInt;
tmp1->push_back((*pRes[0])[i]);
tmp.push_back(tmp1);
}
vvInt vtmp;
for (int i=0;i<tmp.size();i++)
vtmp.push_back(*tmp[i]);

//使用for循环求的最终笛卡尔积结果
for (int i=1;i<pRes.size();i++)
vtmp=multi(vtmp,*pRes[i]);

//打印计算结果
for (int i=0;i<vtmp.size();i++)
{
for (int j=0;j<vtmp[i].size();j++)
cout << vtmp[i][j] << " ";
cout << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐