[leetcode]16 Valid Palindrome

来源:互联网 发布:有关人工智能的文献 编辑:程序博客网 时间:2024/06/10 00:45

题目连接:https://oj.leetcode.com/problems/valid-palindrome/
Runtimes:16ms

1、问题

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.

2、分析

检查一个字符串是否是回文字符串,只考虑数字和字母(忽略大小写)。定义头尾两个下标i,j,往中间扫描,遇到非字母数字跳过,遇到都是字母检查是否相等。直到i > j结束。

3、小结

该字符串是一个句子,包含标点符号,但是题目要求只考虑数字字母,因此需要跳过符号,其次大小写字母的ASCII码相差32。只需一次线性扫描,时间复杂度为O(n),空间复杂度为O(1)。

4、实现

class Solution {public:    bool isLetter(char a)    {        if ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || (a >= '0' && a <= '9'))        {            return true;        }        else            return false;    }    bool isEqual(char a, char b)    {        if (a == b || a - b == 32 || a - b == -32)            return true;        else            return false;    }    bool isPalindrome(string s) {        for (int i = 0, j = s.size() - 1; i < j;)        {            while (!isLetter(s[i]))                i++;            while (!isLetter(s[j]))                j--;            if (i < j && !isEqual(s[i], s[j]))            {                return false;            }            else{                i++;                j--;            }        }        return true;    }};

5、反思

程序比较简单,但是在写的过程中也出现’==’写成’=’,’a <= ‘a”写成’a < ‘a”的低级错误。代码中也把空字符串也当做回文串处理。
文章链接:http://blog.csdn.net/linhuanmars/article/details/22775045

0 0