#415 Valid Palindrome

来源:互联网 发布:博客源码 编辑:程序博客网 时间:2024/06/05 19:16

题目描述:

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.

Challenge 

O(n) time without extra memory.

题目思路:

这题还是two pointers的想法,分别设一个l在string的最左,一个r在string的最右,然后慢慢向对移动,遇到不是数字或者字母的就跳过,出循环的条件是l<r,return false的条件是所指的对象不相同。

Mycode(AC = 34ms):

class Solution {public:    /**     * @param s A string     * @return Whether the string is a valid palindrome     */    bool isPalindrome(string& s) {        // Write your code here                // two pointers to check whether s[l] == s[r]        int l = 0, r = s.length() - 1;        while (l < r) {            while (l < r && !isAlphaNum(tolower(s[l]))) {                l++;            }            while (l < r && !isAlphaNum(tolower(s[r]))) {                r--;            }                        if (l >= r) break;                        if (tolower(s[l]) != tolower(s[r])) return false;            l++;            r--;        }                return true;    }        // return true if ch is alphanumerical    bool isAlphaNum(char ch) {        return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');    }};


0 0
原创粉丝点击