程序员人生 网站导航

【LeetCode】125. Valid Palindrome

栏目:php教程时间:2017-02-04 09:01:43

问题描写

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.

回文字符串判断,但只判断字母和数字是不是构成回文字符串,标点符号被略过。

问题分析

保存左右两个指针,每轮先移动左指针获得1个字母或数字,其它字符都跳过;然后移动右指针,找到1个字母或数字,其它字符都跳过;如果此时左右两个字符都为字母或数字并但是两个不相等,则返回false;进行下轮指针移动直到两个指针相等。

代码

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.length()==0||s.length()==1) return true;
        int left=0, right=s.length()-1;
        // 大写转小写
        for(int i=0;i<s.length();i++) {
            char ch = s[i];
            if(ch>='A'&&ch<='Z') ch = 'a' + ch - 'A';
            s[i] = ch;
        }
        while(left<right) {
            char l = s[left++];
            char r = s[right--];
            while(!((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&left<s.length()) {
                l = s[left++];
            }
            while(!((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&right>0) {
                r = s[right--];
            }
            if(((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&r!=l) {
                return false;
            }
        }
        return true;
    }
};
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐