C++代码
typedef struct SString
{
char ch[100] ;
int length=0;
SString *i;
SString *j;
};
void CreateSString(SString& s1)
{
char m;
int n;
cout << "请输入主串长度" << endl;
cin >> n;
for (int i = 1; i < n+1; i++)
{
cout << "请输入" << i << "个数" << endl;
cin >> m;
s1.ch[i] = m;
s1.length++;
}
cout << "主串为:";
for (int i = 1; i < n+1; i++)
{
cout << s1.ch[i];
}
}
void CreateSString1(SString& s2)
{
;
char x;
int y;
cout << "请输入子串长度" << endl;
cin >> y;
for (int i = 1; i < y+1; i++)
{
cout << "请输入" << i << "个数" << endl;
cin >> x;
s2.ch[i] = x;
s2.length++;
}
cout << "子串为:";
for (int i = 1; i < y+1; i++)
{
cout << s2.ch[i];
}
}
int Index(SString s1, SString s2)
{
int j=1, i = 1;
while (i <= s1.length && j <= s2.length)
{
if (s1.ch[i] == s2.ch[j])
{
i++;
j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if (j > s2.length)
return i - s2.length;
else
return 0;
}
int Index_SXL(SString s1, SString s2, int next[])
{
int j=1, i = 1;
while (i <= s1.length && j <= s2.length)
{
if (j==0||s1.ch[i] ==s2.ch[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j > s2.length)
return i - s2.length;
else
return 0;
}
int main()
{
clock_t t1, t2;
SString s1;
CreateSString(s1);
cout << endl;
SString s2;
CreateSString1(s2);
int next[6] = { 0,0,1,2,3,4};
cout << endl;
cout << "垃圾算法:" << endl;
cout << "该数在字符串第" ;
t1 = clock();
for (int i = 0; i < 10000; i++)
{
Index(s1, s2);
}
cout << Index(s1, s2)<<endl;
t1 = clock()-t1;
printf("垃圾算法耗时:% lf", ((float)t1) / CLOCKS_PER_SEC);
cout << endl;
cout << "SXL算法:" << endl;
cout << "该数在字符串第";
t2 = clock();
for(int i=0;i<10000;i++)
{
Index_SXL(s1, s2, next);
}
cout << Index_SXL(s1, s2, next) << endl;
t2 = clock() - t2;
printf("SXL算法耗时:% lf", ((float)t2) / CLOCKS_PER_SEC);
cout << endl;
}