编程判断字符串是否为回文
来源:互联网 发布:遗传算法 图像处理 编辑:程序博客网 时间:2024/06/03 21:17
判断一个字符串是否为回文,比如说单词“level”就是回文。我们可以从一个字符串的两端进行遍历比较,例如对于level我们可以进行下面的步骤。
(1)计算需要比较的次数。由于“level”字符串长度为5,是奇数,因此比较两次
(2)第一次比较:看“level”的第一个字符与最后一个字符是否相等,若相等,则进行第二次比较。
(3)第二次比较:看“level”的第二个字符与倒数第二个字符是否相等,若相等则是回文
如果在上面的比较过程中有一个不相等,则字符串不是回文。根据上面的思路,我们可以写出如下的程序代码:
#include <iostream>using namespace std ;int IsRevStr(char *str ){ int i,len ; int found = 1 ; //1表示是回文 0则不是 if(str == NULL) { return -1 ; } len = strlen(str) ; for(i = 0 ;i<len/2;i++) //遍历中如果发现相应的头尾字符串不等,则字符串不是回文 { if(*(str+1) != *(str+len-i-1)) { found = 0 ; break ; } } return found ;}int main(){char str1[10] = "1234321" ;char str2[10] = "1234221" ;int test1 = IsRevStr(str1) ;int test2 = IsRevStr(str2) ;cout<<"str1 is "<<(test1 == 1 ? "" : "not")<<"reverse string."<<endl ;cout<<"str2 is "<<(test2 == 1 ? "" : "not")<<"reverse string."<<endl ;return 0 ;}
这个程序中的IsRevStr()函数用于判断字符串是否为回文字符串,如果是则返回1,否则返回0.输出结果:1 str1 is reverse string.
2 str2 is not reverse string.
0 0
- 编程判断字符串是否为回文
- 编程判断字符串是否为回文 判断一个字符串是否是回文,例如单词‘level’
- 判断字符串是否为回文
- 判断字符串是否为回文
- 判断字符串是否为”回文“
- 判断字符串是否为回文
- 判断字符串是否为回文
- 判断字符串是否为回文
- 判断字符串是否为回文
- 判断是否为回文字符串
- 判断字符串是否为回文
- 判断字符串是否为回文字符串
- 判断字符串是否为回文字符串
- 判断字符串是否为回文字符串
- 3-2 判断字符串是否为回文
- java判断字符串是否为回文?
- 判断一个字符串是否为回文
- 判断一个字符串是否为回文
- POJ
- 第一个python实现的mapreduce程序
- HTTP状态码大全(转自wiki)
- 小白题解 Codeforces 805A Fake NP
- 贪心算法的思想
- 编程判断字符串是否为回文
- 项目目标和范围管理 技能点六
- LeetCode128 Longest Consecutive Sequence
- [树] [线段树] 树2
- 常见的502问题
- LeetCode129 Sum Root to Leaf Numbers
- 工厂方法模式——简单到抽象
- 关于matlab GUI 中 多个plot(handles.axes) 无法hold on的问题
- PHP连接数据库、创建数据库、创建表的三种方式