日安!我们的老师要求我们判断一个单词或一系列数字是回文还是不使用堆栈。我已经做完了。但我想练习得更多,所以现在我正在尝试通过删除空格和其他不相关的字符来确定一个句子是否为回文(注:不再是我作业的一部分)我的代码已经在工作(希望如此),但我发现它很混乱。所以我想要改进它。我想删除goto函数,因为我的老师建议我不要使用它。如何使用goto函数退出if语句?提前谢谢你。还有其他方法可以检查句子是否为回文,因为我的代码是用蛮力方法完成的。我的代码如下:注意(我没有在这里包含/粘贴结构、弹出和推送函数)
int main(){
char word[11];
char temp[11];
char value;
int i=0, x=0, n=0, length=0;
Stack*head = NULL;
printf("Please type the word: ");
gets(word);
length = strlen(word);
while(i<length){
if(isspace(word[i]) || !isalpha(word[i])) {
if(isdigit(word[i])) goto NEXT; // i used the goto function here
i++;
continue;
}
NEXT:
temp[n]=word[i];
push(&head, word[i]);
i++;
n++;
}
temp[n]='\0';
while(x<n){
value = pop(&head);
if (value==temp[x]){
x++;
continue;
}
break;
}
if(x==n) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}基于你的建议。以下是我改进后的代码:
int main(){
char word[11];
char temp[11];
int i=0, n=0;
int flag = 1;
Stack*head = NULL;
printf("Please type the word: ");
fgets(word, 11, stdin);
for(i = 0; word[i]!='\0' ; i++){
if(isalnum(word[i])) {
temp[n]=word[i];
push(&head, word[i]);
n++;
}
}
temp[n]='\0';
for(i=0; temp[i]!='\0'; i++){
if (pop(&head)!=temp[i]){
flag = 0;
break;
}
}
if (flag==1) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}发布于 2010-12-13 21:03:44
我喜欢你的态度。
首先,您在这里尝试做的是嵌套两个逻辑语句,它们本质上是一个逻辑语句。您还使用了错误的函数来确定字符类型:
如果为isspace(word[i]),则可以保证!isalpha(word[i])。这两种说法总是对或错,所以其中一种是多余的。你真正要做的是只在字母数字的情况下推送字符,对吧?因此,与其使用if语句来确定是否要跳过某个字符,不如使用if语句来确定是否要推入该字符。我想isalnum()可能就是你想要的。
其次,不是执行strlen()来迭代字符串并使用返回值来迭代字符串(这会造成两次),而是尝试:
while('\0' != word[i])或者更好:
for(i = 0; '\0' != word[i]; i++)最后,您对回文的测试可以稍微整理一下。在循环之后测试循环值在所有情况下都有效,但有点难看。它也不会欣然容忍愚蠢的人。在专业的环境中,有很多人编辑代码,在循环之后使用循环值,这可能是有风险的。也许可以使用一个类似于"match“的布尔值,并将其初始化为true,然后循环到堆栈的末尾,或者"match”变为false,如果堆栈上的字符与预期值不“匹配”,则将"match“设置为false。这也会更有效率。
我正在写这个答案的时候,原来的问题显然被删除了。
如果你想让我发布一个代码示例,我很乐意这样做,但我认为如果我不这样做,你可能会学到更多。如果你想要一个代码示例,或者想让我看看你在回答这个问题后提出了什么,请随意。
发布于 2010-12-13 21:03:51
您可以进行的最简单更改如下:
...
if(isspace(word[i]) || !isalpha(word[i])) {
if(!isdigit(word[i])) {
i++;
continue;
}
}
temp[n]=word[i];
...你还可以做一些其他的事情来整理代码(例如,组合if语句,去掉isspace,因为!isalpha涵盖了这些内容,等等)。
发布于 2010-12-13 21:11:03
我只是瞥了一眼over..might就误会了:
while(i<length){
if(isalnum(word[i])) {
temp[n]=word[i];
push(&head, word[i]);
n++;
}
i++;}
https://stackoverflow.com/questions/4429033
复制相似问题