博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#125. Valid Palindrome
阅读量:4197 次
发布时间:2019-05-26

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

一天一道LeetCode

本系列文章已全部上传至我的github,地址:

欢迎大家关注我的新浪微博,
欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:判断一个字符串是不是有效的回文字符串。忽略里面除了数字和字母的其他字符。

解题思路:两个指针i和j,i从前往后,j从后往前,碰到p[i]和p[j]都是字母或者数字就比较大小,如果相等就i++,j–反之则返回false

直到i>=j时,说明是有效回文,返回true。

//isalnum()是判断该字符是不是字母或数字class Solution {public:    bool isPalindrome(string s) {        int len = s.length();        int i = 0;        int j = len-1;        while(i<=j)        {            while(!isalnum(s[i])&&i<=j) i++;//直到s[i]为字母或数字为止            while(!isalnum(s[j])&&i<=j) j--;//直到s[j]为字母或数字为止            if(i<=j&&tolower(s[i])!=tolower(s[j])) return false;//如果不等就返回false            i++;j--;//反之就继续比较        }        return true;    }};
你可能感兴趣的文章
【一天一道LeetCode】#122. Best Time to Buy and Sell Stock II
查看>>
【一天一道LeetCode】#125. Valid Palindrome
查看>>
【一天一道LeetCode】#231. Power of Two
查看>>
【一天一道LeetCode】#202. Happy Number
查看>>
带你深入理解STL之Vector容器
查看>>
带你深入理解STL之Deque容器
查看>>
带你深入理解STL之Stack和Queue
查看>>
带你深入理解STL之Set和Map
查看>>
Redis源码剖析--源码结构解析
查看>>
Redis源码剖析--动态字符串SDS
查看>>
Redis源码剖析--双端链表Sdlist
查看>>
Redis源码剖析--字典dict
查看>>
Redis源码剖析--跳跃表zskiplist
查看>>
Redis源码剖析--整数集合Intset
查看>>
Redis源码剖析--对象object
查看>>
Redis源码剖析--字符串t_string
查看>>
Redis源码剖析--快速列表quicklist
查看>>
Redis源码剖析--列表list
查看>>
Android开发学习 之 五、基本界面控件-4时间控件
查看>>
详细解读Jquery的$.get(),$.post(),$.ajax(),$.getJSON()用法
查看>>