【LeetCode & 剑指offer刷题】字符串题12:Valid Palindrome(回文词系列)

【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 ;
    }
};
 

 

posted @ 2019-01-05 16:04 wikiwen 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值