zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】字符串题12:Valid Palindrome(回文词系列)

    Valid Palindrome

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
    Note: For the purpose of this problem, we define empty string as valid palindrome.
    Example 1:
    Input: "A man, a plan, a canal: Panama"
    Output: true
    Example 2:
    Input: "race a car"
    Output: false
     
    //问题:回文(判断一个字符串是否是回文的,这里仅考虑字母数字字符,且忽略大小写
    //方法:双指针法,分别从开头和结尾扫描
    using namespace std;
    #include <locale> //本地化库的一部分,包含字符分类、转换等函数
    class Solution
    {
    public:
        bool isPalindrome(string s)
        {
            for(int i=0,j=s.size()-1; i<j; i++,j--)//双指针,分别从开头和结尾开始扫描
            {
                while(isalnum(s[i]) == false && i<j) i++; //如果不是字母数字字符(alphanumeric),增加左指针
                while(isalnum(s[j]) == false && i<j) j--; //如果不是字母数字字符(alphanumeric),增加右指针
               
                if(toupper(s[i]) != toupper(s[j])) return false; //如果不匹配就退出
            }
            return true;
        }
    };
     
     
    680. Valid Palindrome II
    Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
    Example 1:
    Input: "aba"
    Output: True
    Example 2:
    Input: "abca"
    Output: True
    Explanation: You could delete the character 'c'.
    Note:
    1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
     
    //问题:回文2(判断一个字符串是否是回文,可以最多删除一个字符,而且字符串中只有小写英文字母,最大长度为50000)
    //方法:双指针法,借用回文1的解法
    #include <iostream>
    class Solution
    {
    public:
        bool validPalindrome(string s)
        {
            for(int i=0,j=s.size()-1; i<j; i++,j--) //双指针,分别从开头和结尾开始扫描
            {
                if(s[i] != s[j]) //扫描到不匹配字符时,删除其中一个,然后继续扫描
                {
                    int i1 = i,j1 = j-1; //“删除”右边元素
                    int i2 = i +1, j2 = j; //“删除”左边元素
                   
                    while(i1<j1 && s[i1] == s[j1]) //继续扫描剩余元素
                    {
                        i1++;
                        j1--;
                    }
                    while(i2<j2 && s[i2] == s[j2])
                    {
                        i2++;
                        j2--;
                    }
                    return i1>=j1 || i2>=j2; //i1>=j1代表已经扫描完毕,字母均匹配
                }
            }
           
            return true;
        }
    };
     
  • 相关阅读:
    JavaScript autoComplete 1.2
    Linux下安装配置git
    《SQL Server 2008从入门到精通》20180627
    《SQL必知必会》知识点汇总
    关于js的setTimeout和setInterval
    关于js的闭包
    web图片类型
    关于绑定事件
    js原型与继承
    关于js的mouseout
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224912.html
Copyright © 2011-2022 走看看