• [LeetCode] Valid Palindrome


    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.

    Hide Tags
     Two Pointers String
     

     注意 extern int toupper(int c); 如果c为小写英文字母,则返回对应的大写字母;否则返回原来的值。

    class Solution {
        public:
            bool isPalindrome(string s) {
                if(s.empty())
                    return true;
    
                int idx1 = 0;
                int idx2 = s.size()-1;
    
                while(idx1 < idx2)
                {
                    while(!isalnum(s[idx1]) && idx1 < idx2)
                    {
                        idx1 ++;
                    }
    
                    while(!isalnum(s[idx2]) && idx1 < idx2)
                    {
                        idx2 --;
                    }
    
                    if(idx1 >= idx2)
                        break;
    
                    if(toupper(s[idx1]) == toupper(s[idx2]))
                    {
                        idx1 ++;
                        idx2 --;
                    }
                    else
                        return false;
                }
                return true;
    
            }
    };

    使用transform 来更改字母的大小写

    class Solution {
        public:
            bool isPalindrome(string s) {
                transform(s.begin(), s.end(), s.begin(), ::tolower);
                auto left = s.begin(), right = prev(s.end());
                while (left < right) {
                    if (!::isalnum(*left)) ++left;
                    else if (!::isalnum(*right)) --right;
                    else if (*left != *right) return false;
                }
                return true;
            }
    };
  • 相关阅读:
    [转]MySQL日志——Undo | Redo
    linux查看系统的硬件信息
    Linux HDD information (SATA/SCSI/SAS/SSD)
    sysbench 0.5使用手册
    MYSQL数据丢失讨论
    innodb_flush_method理解
    快速从mysqldump文件中恢复一个表
    Python 交互模式中 Delete/Backspace 键乱码问题
    Django--源码安装
    greenplum-时间处理
  • 原文地址:https://www.cnblogs.com/diegodu/p/4422585.html
Copyright © 2020-2023  润新知