84.Valid Palindrome
2016-01-24 21:26
106 查看
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
分析:做这个题目的关键是理清题目的思路,看清判断一个字符串是否是回文的,忽略字符的大小写,并且值关注字母与数字,无视其他字符如标点符号。
Step1:把字符串先转化为小写;
Step2:分别有两个下标i和j,分别向后和向前移动得到当前的字符c1和c2,如果有字符不是数字或小写字母,则无视这个继续移动一步。
Step3:继续循环的条件是i>j;
For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
分析:做这个题目的关键是理清题目的思路,看清判断一个字符串是否是回文的,忽略字符的大小写,并且值关注字母与数字,无视其他字符如标点符号。
Step1:把字符串先转化为小写;
Step2:分别有两个下标i和j,分别向后和向前移动得到当前的字符c1和c2,如果有字符不是数字或小写字母,则无视这个继续移动一步。
Step3:继续循环的条件是i>j;
/** * 判断一个字符串是否是回文的,忽略字符的大小写,并且值关注字母与数字,无视其他字符如标点符号。 * Step1:把字符串先转化为小写; * Step2:分别有两个下标i和j,分别向后和向前移动得到当前的字符c1和c2,如果有字符不是数字或小写字母,则无视这个继续移动一步。 * Step3:继续循环的条件是i>j; */ public boolean isPalindrome(String s) { s = s.toLowerCase(); char sArr[] = s.toCharArray(); int len = sArr.length; if(len<=0){ return true; }else{ int i = 0; int j = len-1; while(i<=j){ char c1 = sArr[i]; char c2 = sArr[j]; /*找到当前符合条件的需要比较的c1,注意数字作为char型时需要加上48*/ while(!(c1>='a' && c1<='z' || c1>=0+48 && c1<=9+48) && i<j){ i++; c1 = sArr[i]; } /*找到当前符合条件的需要比较的c2*/ while(!(c2>='a' && c2<='z' || c2>=0+48 && c2<=9+48) && i<j){ j--; c2 = sArr[j]; } if(c1 != c2){ return false; } i++; j--; } } return true; }
相关文章推荐
- strlen 与 sizeof 的区别
- 页面动态显示当前时间
- android147 360 程序锁fragment
- POI调用Word动态传参
- linux gvim configuration
- redis启动过程
- 基于密度的聚类
- Thinkphp源码分析-命名空间自动加载
- 分布式文件存储FastDFS(四)配置fastdfs-apache-module
- <LeetCode OJ> 43. Multiply Strings
- StreamingAssets文件
- plsql客户端字符集设置
- Leetcode 191 Number of 1 Bits 位运算
- Jacob调用打印机打印Word
- 好句
- 关于gitlab,gerrit
- 机器学习实战(Python)总结
- 如何在caffe中添加新的layer
- 【软工】软工思想
- 《笨办法学Python》 第21课手记