【初级算法】16. 验证回文字符串
2018-05-03 13:21
274 查看
题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true 示例 2: 输入: "race a car" 输出: false
1.解题思路:
本题比较简单,直接取字符串的前后字母进行比对,如果相等则前进,否则返回错误。
class Solution { public: bool isPalindrome(string s) { int len = s.size(); int start = 0; int end = len-1; while(start < end){ char first,second; /*get the fisrt char*/ while(start <= end){ if((s[start] >= 'a' && s[start] <= 'z')|| (s[start] >= 'A' && s[start] <= 'Z')|| (s[start] >= '0' && s[start] <= '9')){ first = s[start]; if(s[start] >= 'A' && s[start] <= 'Z'){ first = first-'A'+'a'; } break; }else{ start++; } } /*get the second char*/ while(start <= end){ if((s[end] >= 'a' && s[end] <= 'z')|| (s[end] >= 'A' && s[end] <= 'Z')|| (s[end] >= '0' && s[end] <= '9')){ second = s[end]; if(second <= 'Z'&&second>='A'){ second = second-'A'+'a'; } break; }else{ end--; } } if(start > end){ break; } if(first == second){ start++; end--; }else{ return false; } } return true; } };
相关文章推荐
- 信用卡必须是 13-16 位的整数串,它必须通过 Luhn 算法来验证通过才是合法的卡号。 Luhn 算法校验的过程是: • 从卡号最后一位数字开始,逆向将奇数位(1、3、5 等)相加。 • 从卡
- 第十四周项目1—验证算法(折半查找)
- 第十六周 -项目1 -算法验证 (7)归并排序 (8)基数排序
- 第十六周 项目1--验证算法(3)--冒泡排序
- C#实现的18位身份证格式验证算法
- C#实现的18位身份证号码最新算法[验证部分]
- 第十三周 项目1-验证算法(2)
- 第11周项目1-验证算法(2)二叉树构造算法的验证
- 第11周项目1-验证算法(4)哈夫曼树
- 第十六周项目一验证算法(6)基数排序
- 线性表16:双向链表 – 数据结构和算法21
- C#实现的18位身份证格式验证算法
- 第十六周项目1-(7)验证算法归并排序
- 第十六周 项目1 验证算法 直接插入排序 折半插入排序
- 第十六周项目1-验证算法(1)直接插入排序
- 第十六周 项目1 验证算法 归并排序
- 第十六周项目1-验证算法(6)堆排序
- 第16周项目1-验证算法(2)希尔排序
- 第11周项目1 验证算法(4)哈夫曼编码的算法验证
- 第十六周项目1-算法验证