随笔- 509  文章- 0  评论- 151  阅读- 22万 

Valid Palindrome

2014.1.13 18:48

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.

Solution:

  This problem doesn't involve maths or difficult algorithms, so it's the kind of easy problem to test if you're careful enough to solve it one-pass. Make NO mistake.

  Time complexity is O(n), where n is the length of the string. Space complexity is O(1).

Accepted code:

复制代码
 1 // 1RE, 1AC, be more careful, could've 1AC~
 2 class Solution {
 3 public:
 4     bool isPalindrome(string s) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         int i, j, len;
 8         
 9         len = s.length();
10         if(len <= 0){
11             return true;
12         }
13         
14         char a, b;
15         
16         i = 0;
17         j = len - 1;
18         while(i < j){
19             if(s[i] >= 'a' && s[i] <= 'z'){
20                 a = s[i];
21             }else if(s[i] >= '0' && s[i] <= '9'){
22                 a = s[i];
23             }else if(s[i] >= 'A' && s[i] <= 'Z'){
24                 a = s[i] - 'A' + 'a';
25             }else{
26                 ++i;
27                 continue;
28             }
29             if(s[j] >= 'a' && s[j] <= 'z'){
30                 b = s[j];
31             }else if(s[j] >= '0' && s[j] <= '9'){
32                 b = s[j];
33             }else if(s[j] >= 'A' && s[j] <= 'Z'){
34                 b = s[j] - 'A' + 'a';
35             }else{
36                 // 1RE here, wrong direction of $j
37                 --j;
38                 continue;
39             }
40             if(a == b){
41                 ++i;
42                 --j;
43             }else{
44                 break;
45             }
46         }
47         
48         return i >= j;
49     }
50 };
复制代码

 

 posted on   zhuli19901106  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示