博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Valid Palindrome
阅读量:4630 次
发布时间:2019-06-09

本文共 1425 字,大约阅读时间需要 4 分钟。

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

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.


解题思路:

使用两个指针,一个从左到右,一个从右到左,当左指针值大于右指针时,说明String 遍历结束。注意:alphanumeric 包括 a-zA-Z0-9,一定要看清题意。

因为忽略大小写,所以就统一为小写。

同时面试时要问清楚当String is empty时,是否是valid palindrome.


Java code:

public boolean isPalindrome(String s) {        if(s.length() == 0){            return true;        }        int p1 = 0, p2 = s.length()-1;  //p1: left to right p2: right to left        s= s.toLowerCase();        while(p1 <= p2){            char left = s.charAt(p1);            char right = s.charAt(p2);            if(!((left >='a' && left <= 'z') || (left >= '0' && left <= '9'))){                p1++;                continue;            }            if(!((right >='a' && right <= 'z') || (right >= '0' && right <= '9'))){                p2--;                continue;            }            if(left != right){                return false;            }else{                p1++;                p2--;            }        }        return true;    }

Reference:

1. http://www.cnblogs.com/springfor/p/3884156.html

 

转载于:https://www.cnblogs.com/anne-vista/p/4848895.html

你可能感兴趣的文章
几种交叉验证(cross validation)方式的比较
查看>>
第44章:MongoDB-集群--Sharding(分片)--分片的片键选择
查看>>
自定义ISO结构
查看>>
7.11 animals.c 程序
查看>>
java Web三大组件--过滤器
查看>>
使用NUnit为游戏项目编写高质量单元测试的思考
查看>>
Uva 1638 Pole Arrangement
查看>>
Java内存泄漏
查看>>
逻辑函数的代数化简法
查看>>
第十一周PSP&进度条
查看>>
hdu 1501 DFS+记忆化搜索
查看>>
试说移动端是如何调试的?
查看>>
常用正则表达式!
查看>>
用JAVA生成老电影海报
查看>>
数组溢界地址的正确使用: 即 int a[6] 中的 a[-1] 和 a[6] 正确使用
查看>>
怎样退出App之前唤醒还有一个App?
查看>>
-bash:jps:command not found
查看>>
cogs 998. [東方S2] 帕秋莉·诺蕾姬
查看>>
BZOJ 1019: [SHOI2008]汉诺塔
查看>>
jquery ocupload一键上传文件应用
查看>>