您的位置:首页 > 其它

两个字符串是否包含的问题

2012-08-18 11:10 218 查看
/*
* 用轮询法来求解两个字符串是否包含的问题 时间复杂度O(m*n)
*
*/
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

bool CompareString(string longstring , string shortstring){
for(int i = 0;i < shortstring.length();i++)
{
int j=0;
while(j < longstring.length())
{
if(longstring[i] != shortstring[j])
{	j++;}
else
{	break;}
}
if(j == longstring.length())
{
cout<<"false"<<endl;
return 0;
}
}
cout<<"true"<<endl;
return 1;
}

int main(int argc, char **argv)
{
string longstring="ABCDEFGHLMNOPQRS";
string shortstring="DCGSRQPOZ";
CompareString(longstring,shortstring);
return 0;
}
/*
* 用对两个字符串先分别排序,然后再同时对两个字符串依次轮询的方法求解两个字符串是否包含的问题 时间复杂度O(mlogm)+O(nlogn)+O(m+n)
*
*/
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;
void Exchange(char &a,char &b)
{
char tmp;
tmp=a;
a=b;
b=tmp;
}

int Partition(string &s,int p,int r)
{
char key=s[r];
int i=p-1;
for(int j = p;j < r;j++)
{
if(s[j] <= key)
{
i=i+1;
Exchange(s[i],s[j]);
}
}
Exchange(s[i+1],s[r]);
return i+1;
}

void QuickSort(string &s,int p,int r)
{
if(p<r)
{
int q=Partition(s,p,r);
QuickSort(s,p,q-1);
QuickSort(s,q+1,r);
}
}

bool CompareString(string s1,string s2)
{
int posOne = 0;
int posTwo = 0;
while(posOne < s1.length() && posTwo < s2.length())
{
while(s1[posOne] < s2[posTwo] && posOne < s1.length()-1)
{	posOne++;}
if(s1[posOne] == s2[posTwo]){	posTwo++;}
else{	break;}
}
if(posTwo == s2.length())
return true;
else return false;
}

int main(int argc, char **argv)
{
string s1="ABCDEFGHLMNOPQRS";
string s2="DCGSRQPOZ";
QuickSort(s1,0,s1.length()-1);
QuickSort(s2,0,s2.length()-1);
//cout<<"***"<<s2<<endl;
cout<<CompareString(s1,s2)<<endl;
return 0;
}

/*
* 使用hashtable的方法求解两个字符串是否包含的问题 时间复杂度为O(m+n)
*
*/
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
string str1="ABCDEFGHLMNOPQRS";
string str2="DCGSRQPOM";
int hash[58];
int num=0;
for(int i=0;i < str2.length();i++)
{
int pos=str2[i]-'A';
hash[pos] = 1;
num++;
}
for(int i=0;i < str1.length();i++)
{
int pos=str1[i] - 'A';
if(hash[pos] == 1)
{
hash[pos] =1;
num--;
}
}
if(num == 0) cout<<"true"<<endl;
else cout<<"false"<<endl;
return 0;
}

/*
* 使用bitmap的方法求解两个字符串是否包含的问题 时间复杂度为O(m+n)
*
*/
#include <iostream>
#include <string>
using namespace std;

#define getbit(x) (0x01 << (x - 'A'))

bool AContainB(string &str1, string &str2)
{
int dict=0;
int j=0;
for(int i=0;i < str1.length();i++)
{
dict=dict | getbit(str1[i]);
}
for (j=0;j < str2.length();j++)
{
if((dict & getbit(str2[j])) != getbit(str2[j]))
break;
}
//cout<<j<<endl;
if(j == str2.length()) return true;
else return false;
}

int main(int argc,char **argv)
{
string str1="ABCDEFGHLMNOPQRS";
string str2="DCGSRQPOZ";
bool res=AContainB(str1,str2);
cout<<res<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string exchange