妙趣横生算法 4:判断字符串是否回文
2012-01-23 23:23 藯蓝枫叶 阅读(491) 评论(0) 编辑 收藏 举报实例说明
“回文”是指顺读和反读内容均相同的字符串,例如,“121”,“ABBA”等。
实例解析
引入两个指针变量,开始时,两指针分别指向字符串的首末字符,当两指针所指字符相等时,两指针分别向后和向前移一个字符位置,并继续比较,直至两指针相遇,说明该字符是回文。若比较过程中,发现两字符不相等,则可以判断该字符串不是回文!
程序代码
#include <stdio.h> #define MAX 50 int cycle(char *s) { char *h,*t; for(h=s,t=s+strlen(s)-1;t>h;h++,t--) { if(*h!=*t) { break; } } return t<=h; } main() { char s[MAX]; while(1) { printf("Please input the string you want to judge(input ^ to quit):"); scanf("%s",s); if(s[0]=='^') { break; } if(cycle(s)) { printf("%s is a cycle string.\n",s); } else { printf("%s is not a cycle string.\n",s); } } printf("\n Thank you for your using,bye bye!\n"); }
个人总结
主要运用指针的强大----可操控性
第一步:两个指针分别指向一头一尾
第二步:移动指针,比较字符
。。。。新年快乐!继续努力!