//暴力轮询法
#include <iostream>
using namespace std;
int Grial(char *str1, char *str2)
{
if (str2 == NULL)return 1;
char *p1 = str1;
char *p2 = str2;
while (*p2 != ‘\0‘)
{
while (*p1 != ‘\0‘)
{
if (*p2 == *p1)
break;
p1++;
}
if (*p1 == ‘\0‘)
return 0;
p2++;
p1 = str1;
}
return 1;
}
int main()
{
char *s1 = "12345678";
char *s2 = "2349";
cout<<Grial(s1, s2)<<endl;
return 0;
}
//bitset解法,比较快的了,比那些用数组来存储以及用hash表来存储更好。
#include <iostream>
#include <bitset>
using namespace std;
int Grial(char *str1, char *str2)
{
bitset<255> bt;
char *p = str1;
while (*p != ‘\0‘)
{
if (bt.test(*p) == 0)
bt.set(*p);
p++;
}
char *q = str2;
while (*q != ‘\0‘)
{
if (bt.test(*q) == 0)
{
return 0;
}
q++;
}
return 1;
}
int main()
{
char *s1 = "1231423";
char *s2 = "239";
cout<<Grial(s1, s2)<<endl;
return 0;
}
//还是用数组写一下吧,hash在这里没有什么意思,建议大家学习第二种方法。
#include <iostream>
using namespace std;
static int b[255];//由于b存储在全局数据区,会自己初始化。
int Grial(char *str1,char *str2)
{
char *p = str1;
char *q = str2;
while (*p != ‘\0‘)
{
b[*p] = 1;
p++;
}
while (*q != ‘\0‘)
{
if (b[*q] == 0)return 0;
q++;
}
return 1;
}
int main()
{
char *s1 = "123456";
char *s2 = "16";
cout<<Grial(s1, s2)<<endl;
return 0;
}
时间: 2024-10-20 10:56:40