让我们假设我有这两个arrays
,int array[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
和int s_array[15] = {1,2,3,4,5}
*请注意,我知道s_array[]
设置为15,但只有5个元素
在我的代码的以下部分中,我想检查s_array[]
是否为array[]
的子序列,这意味着存储在s_array[]
中的所有值也存储在array[]
中,并且订购。这意味着{3,5,4}
不是子序列,而{3,4,5}
是子序列。
这是代码的一部分(我认为问题出在其中)。 j
是s_array[]
中的数字。整个代码将显示在下面
for( i = 0; i < 15; i++ ){
if( s_array[0] == array[i] ){ /*if the first element of the s_array is not
available then it is not a sub-sequence and
there is no need to check the rest */
for( Bcount = 1; Bcount < ( j - 1 ); Bcount++ ){
if( s_array[Bcount] == array[Bcount + i])
counter++;
else{
printf( "B is not a sub-sequence of A." );
break;
}
}
if( j == counter ){
printf( "B is a sub-sequence of A." );
break;
}
}
else
continue;
}
完整的代码供有兴趣的人使用,或者有助于更好地理解
#include <stdio.h>
int main(){
int array[15], s_array[15], i = 0, j = 0, Bcount = 1, counter = 1;
printf( "Please enter a sequence A: " );
while(i < 15 && scanf("%d", &array[i]) == 1) {
//input for array[], will always have 15 elements
i++;
if( i == 15){
printf( "Please enter a sequence B: " );
while(j < 15 && scanf("%d", &s_array[j]) == 1) {
//input for s_array, will have somewhere between 1 and 15 elements
j++;
}
for( i = 0; i < 15; i++ ){
if( s_array[0] == array[i] ){
for( Bcount = 1; Bcount < ( j - 1 ); Bcount++ ){
if( s_array[Bcount] == array[Bcount + i])
counter++;
else{
printf( "B is not a sub-sequence of A." );
break;
}
}
if( j == counter ){
printf( "B is a sub-sequence of A." );
break;
}
}
else
continue;
}
return 5;
}
}
return 0;
}
最佳答案
您可以遍历array
并为s_array
设置索引计数器。如果仅array[i] == s_array[j]
,则增加该计数器,否则重置。
您可以在以下情况下更早地结束循环:
您已经找到子数组
没有足够的元素在数组中进行比较
代码示例:
#include <stdio.h>
#include<stdbool.h>
int main(void)
{
int array[15] = {1, 2, 3, 4, 6, 7, 6, 9, 0, 1, 2, 3, 4, 5, 6};
int s_array[5] = {2, 3, 4, 5, 6};
const int size_array = sizeof(array) / sizeof(array[0]);
const int size_s_array = sizeof(s_array) / sizeof(s_array[0]);
bool isFound = false;
if (size_s_array > size_array)
{
printf("Sub array is larger than the array\n");
}
else
{
int j = 0;
for (int i = 0; (i < size_array) && (j != size_s_array) ; i++)
{
if (array[i] == s_array[j])
{
j++;
}
else
{
j = 0;
if (i > size_array - size_s_array) // You can also put this in for loop's test condition, but I find this more readable.
{
break;
}
}
}
isFound = (j == size_s_array) ? true : false;
}
printf("%s\n", isFound ? "Found" : "Not found");
return 0;
}
不同s_array的测试用例:
array[15] = {1, 2, 3, 4, 6, 7, 6, 9, 0, 1, 2, 3, 4, 5, 6};
int s_array[5] = {2, 3, 4, 5, 6};
Found
int s_array[1] = {8};
Not found
int s_array[2] = {1, 2};
Found
int s_array[15] = {1, 2, 3, 4, 6, 7, 6, 9, 0, 1, 2, 3, 4, 5, 6};
Found
int s_array[16] = {0, 1, 2, 3, 4, 6, 7, 6, 9, 0, 1, 2, 3, 4, 5, 6};
Sub array is larger than the array
Not found
int s_array[2] = {0, 2};
Not found
关于c - 查找一个数组是否是另一个数组的子序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47560607/