有一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。
int findnum(int a[][4], int x, int y, int f) //第一个参数的类型需要调整
{
int i = 0, j = y - 1; //从右上角开始遍历
while (j >= 0 && i < x)
{
if (a[i][j] < f) //比我大就向下
{
i++;
}
else if (a[i][j] > f) //比我小就向左
{
j--;
}
else
{
return 1;
}
}
return 0;
}
void main()
{
int a[4][5] =
{
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};
int i = findnum(a, 4, 5, 77);
if (i)
printf("Success");
else
printf("Failed");
}
实现一个函数,可以左旋字符串中的k个字符。
例如:
ABCD左旋一个字符得到BCDA
ABCD左旋两个字符得到CDAB
//实现一个函数,可以左旋字符串中的k个字符。
//例如:
// ABCDABCD
//ABCD左旋一个字符得到BCDA
//ABCD左旋两个字符得到CDAB
void spin1(char *result, char* s, int n)
{
int sn = strlen(s);
int n1 = n % sn;
for (int k = 0; k < n1; ++k)
{
*(result+sn - n1 + k) = *(s + k);
}
for (int j = 0; j < sn - n1; ++j)
{
*(result+j) = *(s + n1+ j);
}
result[sn] = '\0';
}
void* spin2(char* result, char* s, int n)
{
int sn = strlen(s);
int n1 = n % sn;
strncpy(result, s+n1, sn-n1);
result[sn - n1] = '\0';
strncat(result, s, n1);
result[sn] = '\0';
}
void main()
{
char s[] = "ABCD";
char result1[20] = "";
spin1(result1, s, 2);
printf("%s\n", result1);
char result2[20] = "";
spin2(result2, s, 2);
printf("%s\n", result2);
}
写一个函数,判断一个字符串是否为另外一个字符串旋转之后的字符串。
例如:给定s1 = AABCD和s2 = BCDAA,返回1
给定s1 = abcd和s2 = ACBD,返回0.
AABCD左旋一个字符得到ABCDA
AABCD左旋两个字符得到BCDAA
AABCD右旋一个字符得到DAABC
//常规做法
int is_True1(char* s1, int n1, char* s2, int n2)
{
int i = 0;
int j = 0;
if (n1 != n2)
return 0;
else
{
for (i = 0; i < n1; ++i)
{
char temp[100];
for (int k = 0; k < i; ++k)
{
temp[k] = *(s1 + (n1 - i + k));
}
for (j = 0; j < n1-i; ++j)
{
temp[i + j] = *(s1 + j);
}
temp[n1] = '\0';
int is = strcmp(temp, s2);
if (is == 0)
{
return 1;
}
}
return 0;
}
}
//方法2:ABCDE无论怎么旋,旋转后的所有结果,都包含在了ABCDEABCD这个字符串里了
int is_True2(char* s1, char* s2)
{
char tmp[256] = { 0 }; //用一个辅助空间将原字符串做成两倍原字符串
strcpy(tmp, s1); //先拷贝一遍
strcat(tmp, s1); //再连接一遍
return strstr(tmp, s2) != NULL; //看看找不找得到
}
void main()
{
char s1[] = "AABCD";
int n1 = strlen(s1);
char s2[] = "CDAAB";
int n2 = strlen(s2);
int i1 = is_True1(s1, n1, s2, n2);
printf("%d\n", i1);
int i2 = is_True2(s1, s2);
printf("%d\n", i2);
}