【发布时间】:2017-11-12 09:24:03
【问题描述】:
我有一个字符串数组,我想在数组中为每个字符串(如果有的话)找到第一个伪回文。所以我决定首先对我的数组进行排序,然后反转单词并对反转的单词进行二进制搜索。所以这就是我到目前为止所拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char len(char *x){
char len = 0;
while (*x != '\0'){
x++;
len++;
}
return len;
}
char compare(char *x, char *y){
char x0 = &x;
char y0 = &y;
while (*x != '\0'){
if (tolower(*x) < tolower(*y)) return -1;
if (tolower(*x) > tolower(*y)) return 1;
x++;
y++;
}
// if we are here it means that strings are equal (case insensitive)
x = &x0;
y = &y0;
while (*x != '\0'){
if (*x > *y) return -1;
if (*x < *y) return 1;
x++;
y++;
}
// strings are equal (case sensitive)
return 0;
}
char *reverse(char *x){
int i, j;
char temp, *rev = NULL;
rev = malloc(sizeof(char)*(len(x)+1));
rev = strcpy(rev,x);
i = 0;
j = len(x) - 1;
while (i < j){
temp = rev[i];
rev[i] = x[j];
rev[j] = temp;
i++;
j--;
}
return rev;
}
int binsearch(char *x, char *A, int len){
int l, r, m, index;
l = 0;
r = len - 1;
index = -1;
while (l <= r){
m = (l + r) / 2;
if (compare(x, A[m]) == 0){
index = m;
r = m - 1;
}
else if (compare(x, A[m]) == -1) r = m - 1;
else l = m + 1;
}
return index;
}
int main()
{
int n, i, j, k, fnd;
char T[10000][101], temp[101];
scanf("%d", &n);
for (i = 0; i < n; i++){
scanf("%s", &T[i]);
}
for (i = 1; i < n; i++){
strcpy(temp, T[i]);
j = i - 1;
while (j >= 0 && compare(T[j], temp) == 1){
strcpy(T[j+1], T[j]);
j--;
}
strcpy(T[j+1], temp);
}
for (i = 0; i < n; i++){
fnd = binsearch(reverse(T[i]), T, n);
printf("%d", fnd);
}
return 0;
}
此程序停止执行。问题可能在于二进制搜索,因为之前的每个函数都执行得很好。但是这个二分搜索有什么问题呢?或者还有什么可以破解密码?
【问题讨论】:
-
请修正缩进
-
回文是一个与自身相反的字符串。两个相互反转的不同字符串不是回文。请弄清楚术语。
-
你不需要写你的
len函数。 C 有一个名为strlen的内置函数,它完全按照您编写的方式进行操作。 -
1.启用编译器警告并将其视为错误。 2. 阅读 strcpy 的手册。它需要什么头文件? 3. 阅读那个 heder 文件的概要。它有你可能想要使用的功能吗?
-
您应该写一个问题,专门询问您收到的错误/警告。不要为此使用 cmets。顺便还有more errors than you cite。
标签: c binary-search palindrome