C语言中,已知64字节unsigned char数组,找出64字节数组中连续相同的16个字节,有什么好的算法吗?
答案:5 悬赏:30 手机版
解决时间 2021-02-22 21:57
- 提问者网友:温柔港
- 2021-02-21 21:29
C语言中,已知64字节unsigned char数组,找出64字节数组中连续相同的16个字节,有什么好的算法吗?
最佳答案
- 五星知识达人网友:爱难随人意
- 2021-02-21 21:47
给你写了一个,你看看,不懂就追问:
#include
int main()
{
unsigned char a[64] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,37,38,39,40,41,42,43,44,45,
46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64};
int i = 0;
int j = 1;
int k = 0;
for (i=0; i<63; i++)
{
if (a[i] == a[i+1])
{
if (0==k)
{
k = i;// 记录起始位置
}
j++;
if (16==j)
{
#include
int main()
{
unsigned char a[64] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,37,38,39,40,41,42,43,44,45,
46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64};
int i = 0;
int j = 1;
int k = 0;
for (i=0; i<63; i++)
{
if (a[i] == a[i+1])
{
if (0==k)
{
k = i;// 记录起始位置
}
j++;
if (16==j)
{
printf("从第%d位到第%d位相同,相同的值为:%d
", k+1, i+2, a[i]); system("pause");
return 0;
}
}
else
{
k=0;
j=1;
}
}
printf("未找到连续16个相同的字节!
"); system("pause");
return 0;
}
运行结果:
全部回答
- 1楼网友:蕴藏春秋
- 2021-02-22 01:38
将数据类型直接改成string类的然后调用里面的find函数很轻松就解决了,具体操作百度string类中find函数的用法
- 2楼网友:山有枢
- 2021-02-22 00:19
模式匹配吗?有个KMP算法你可以百度学习下
- 3楼网友:拾荒鲤
- 2021-02-21 23:29
我的一个算法是一次最多一次遍历数组即可,所以算法时间复杂度为o(n),算法如下:
单次循环遍历数组,在循环中有两下标,前一个下标与后一个下标进行比较,相等,后一下标后指,不等前一下标指向后一下标,后一下标指向下一个下标,继续循环。
代码如下:(注意,百度知道粘贴源码时没有保留我的格式。。。)
//size:the size of array, n: the number of char is the same. you can initial size = 64 and n = 16
int findTheSame(unsigned char* array, int size, int n){
unsigned char pre = array;
unsigned char cur = array+1;
int count = 0;
while(cur != array + size && count < n){
if(*pre != *cur){
pre = cur;
count = 0;
}
else{
count++;
}
cur++;
}
return count < n ? (pre - array) : -1;
}
单次循环遍历数组,在循环中有两下标,前一个下标与后一个下标进行比较,相等,后一下标后指,不等前一下标指向后一下标,后一下标指向下一个下标,继续循环。
代码如下:(注意,百度知道粘贴源码时没有保留我的格式。。。)
//size:the size of array, n: the number of char is the same. you can initial size = 64 and n = 16
int findTheSame(unsigned char* array, int size, int n){
unsigned char pre = array;
unsigned char cur = array+1;
int count = 0;
while(cur != array + size && count < n){
if(*pre != *cur){
pre = cur;
count = 0;
}
else{
count++;
}
cur++;
}
return count < n ? (pre - array) : -1;
}
- 4楼网友:西岸风
- 2021-02-21 23:14
//a[] = 0,0,0,0,1,1,1,1,1,1,1,0,1,1,1,0
//b[] = 1,2,3,4,1,2,3,4,5,6,7,1,1,2,3,1 //count array
#include
#define N 16
int main()
{
unsigned char a[N]={0,0,0,0,1,1,1,1,1,1,1,0,1,1,1,0};
int b[N]={1};
int i;
for(i=1;i {
if(a[i]==a[i-1]) b[i]=b[i-1]+1;
else b[i]=1;
}
for(i=0;i printf("\n");
return 0;
}
//b[] = 1,2,3,4,1,2,3,4,5,6,7,1,1,2,3,1 //count array
#include
#define N 16
int main()
{
unsigned char a[N]={0,0,0,0,1,1,1,1,1,1,1,0,1,1,1,0};
int b[N]={1};
int i;
for(i=1;i
if(a[i]==a[i-1]) b[i]=b[i-1]+1;
else b[i]=1;
}
for(i=0;i
return 0;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯