博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Valid Palindrome 验证回文字符串
阅读量:7040 次
发布时间:2019-06-28

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

 

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

Notice

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.

 
Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

O(n) time without extra memory.

 

LeetCode上的原题,请参见我之前的博客。

 

解法一:

class Solution {public:    /**     * @param s A string     * @return Whether the string is a valid palindrome     */    bool isPalindrome(string& s) {        int left = 0, right = s.size() - 1;        while (left < right) {            if (!isAlNum(s[left])) ++left;            else if (!isAlNum(s[right])) --right;            else if ((s[left] + 32 - 'a') % 32 != (s[right] + 32 - 'a') % 32) return false;            else {                ++left; --right;            }        }        return true;    }    bool isAlNum(char c) {        if (c >= 'a' && c <= 'z') return true;        if (c >= 'A' && c <= 'Z') return true;        if (c >= '0' && c <= '9') return true;        return false;    }};

 

解法二:

class Solution {public:    /**     * @param s A string     * @return Whether the string is a valid palindrome     */    bool isPalindrome(string& s) {        int left = 0, right = s.size() - 1;        while (left < right) {            if (!isalnum(s[left])) ++left;            else if (!isalnum(s[right])) --right;            else if ((s[left] + 32 - 'a') % 32 != (s[right] + 32 - 'a') % 32) return false;            else {                ++left; --right;            }        }        return true;    }};

 

转载地址:http://nsxal.baihongyu.com/

你可能感兴趣的文章
MySQL内核月报 2014.10-MySQL· 捉虫动态·崩溃恢复失败
查看>>
IOS开发之绝对布局和相对布局(屏幕适配)
查看>>
算法设计与分析 上机题Mergesort
查看>>
WinForm 清空界面控件值的小技巧
查看>>
jQuery源码-dom操作之jQuery.fn.html
查看>>
IOS bug之Code Sign error:Provisioning profile
查看>>
Win10系统菜单打不开问题的解决,难道是Win10的一个Bug ?
查看>>
Xcode连接git@osc
查看>>
【Oracle】Current online Redo 和 Undo 损坏的处理方法
查看>>
TLTagsControl
查看>>
Linux内核中SPI总线驱动分析
查看>>
Java8中CAS的增强
查看>>
C语言之将无符号字符型转化为ascii码值
查看>>
maven2完全使用手册
查看>>
SQL应用与开发:(一)导论和环境
查看>>
简单封装quartz实现任务调度的配置和管理
查看>>
Android Matrix详解
查看>>
JVM 堆栈区域数据存放流程
查看>>
【MyBatis框架】配置文件-resultMap总结
查看>>
JSP生成验证码
查看>>