• leetcode-125 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.

    只考虑数字和字母,忽略大小写,求是否是回文。一开始我的思路很简单,用一个新string存翻转后的字符串再和原来的比较

    class Solution {
    
    public:
       bool isPalindrome(string s) {
            if (s.empty())
                return true;
            string newS;
            for (char c : s)
            {
                if (isAlphaNumeric(c))
                {
                    if ((c >= 'a') && (c <= 'z'))
                        c = c - 32;
        
                    newS += c;
                }
            }
            string b = newS;
            reverse(newS.begin(), newS.end());
            if (newS == b)
                return true;
            else
                return false;
       }
        inline bool isAlphaNumeric(const char &c)
        {
            if ((c >= '0' && c <= '9') || ((c >= 'A') && (c<='Z')) || ((c>='a') && (c <= 'z')))
                return true;
            else
                return false;
        }
    
    };

     觉得这样太慢了,就改用之前学到的两点法,一个从前往后,一个从后往前,不用再弄新数组。 

    class Solution {
        //改用两点法
    public:
        bool isPalindrome(string s) {
            if(s.empty())
                return true;
            int length = s.size();
            int i=0,j=length-1;
            while(i<j)
            {
                while(i<j && !isAlphaNumeric(s[i])) ++i;
                while(i<j && !isAlphaNumeric(s[j])) --j;
                 
    
                if(i>=j) break;  
                if(s[i] != s[j])
                    return false;
                
                ++i;
                --j;
            }
            return true;
        }
        inline bool isAlphaNumeric (char &c)
        {
            c = lowerCase(c);
             if ((c >= '0' && c <= '9') || ((c >= 'A') && (c<='Z')) || ((c>='a') && (c <= 'z')))
                return true;
            else 
                return false;
        }
        inline char lowerCase( char c) 
        {  
            if( c>='A' && c<='Z') return c + 'a' - 'A';  
            else return c;  
        } 
    
    };
  • 相关阅读:
    贪吃蛇 666
    安装postgresql
    linux CentOS6.5 yum安装mysql 5.6
    centos--git搭建之Gogs安装
    查看mysql 默认端口号和修改端口号
    centos之mysql安装配置使用
    流媒体服务器SRS部署
    vue用webpack打包时引入es2015插件
    log4j2的log输出到tomcat/logs目录下及使用(转)
    log4j2的配置文件log4j2.xml笔记
  • 原文地址:https://www.cnblogs.com/tonychen-tobeTopCoder/p/5164421.html
Copyright © 2020-2023  润新知