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

    思路1:首先定义一个函数判断一个字符是不是符合规则——字符和数字(不包含空格、标点符号等),然后在按照判断回文结构的经典规则,定义前后两个指针,如果前后两个指针的内容不符合规则,则begin++,end--,再者判断是否为回文结构。

    class Solution {
    public:
        bool isChar(char &ch)
        {
            if(ch>='0' && ch<='9')
                return true;
            else if(ch>='a' && ch<='z')
                return true;
            else if(ch>='A'&&ch<='Z')
            {
                ch+=32;
                return true;
            }
            return false;
        }
        bool isPalindrome(string s) {
            if(s=="")
                return true;
            int n=s.size();
            int begin=0;
            int end=n-1;
            while(begin<end)
            {
                if(!isChar(s[begin]))
                    begin++;
                else if(!isChar(s[end]))
                    end--;
                else if(s[begin++]!=s[end--])
                {
                    return false;
                }
            }
            return true;
        }
    };

    思路2:设置一个字符串变量str,将原字符串中数字和字符不包含标点空格等纳入str,如果出现大写字母,则将其转变为小写字母。这样就得到了只包含字符和数字的字符串了,然后判断其是否为回文串。

    class Solution {
    public:
        bool isPalindrome(string s) {
            if(s=="")
                return true;
            string str="";
            int n=s.size();
            for(int i=0;i<n;i++)
            {
                if((s[i]>='a'&&s[i]<='z')||(s[i]>='0'&&s[i]<='9')||(s[i]>='A'&&s[i]<='Z'))
                {
                    if(s[i]>='A'&&s[i]<='Z')
                        str+=(s[i]-'A'+'a');
                    else
                        str+=s[i];
                }
            }
            for(int i=0;i<str.size();i++)
            {
                if(str[i]!=str[str.size()-i-1])
                    return false;
            }
            return true;
        }
    };
  • 相关阅读:
    linux centos7 如何安装mysql
    Json转换 在java中的应用
    最最简单的spring mvc + Maven项目
    windows下 申请免费ssl证书的方法 (letsencrypt)
    PowerDesigner中Table视图同时显示Code和Name
    在linux中 部署 mongo 数据库服务端
    Java保存图片到数据库Blob格式
    MyBatis mapper记录
    vue防止多次点击,重复请求
    金额的单位转换,元转分
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3739404.html
Copyright © 2020-2023  润新知