leetcode 680. Valid Palindrome II

1.题目

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

2.分析

从两端向中间遍历字符串,当遇到左右两端字符不相等时,有两种删除的可能:
删除左边的字符 or 删除右边的字符
对这两种情况再判断是否回文即可。

3.代码

方法1:

class Solution {
public:
    bool validPalindrome(string s) {
        int c1 = 0, c2 = 0;
        int l = 0, r = s.size() - 1;
        while (l < r) {
            if (s[l] != s[r])
            {
                ++l;//删除左边的字符
                c1 += 1;
            }
            else {
                ++l;
                --r;
            }
        }
        l = 0, r = s.size() - 1;
        while (l < r) {
            if (s[l] != s[r]) {
                --r;//删除右边的字符
                c2 += 1;
            }
            else {
                ++l;
                --r;
            }
        }
        return c1 < 2 || c2 < 2;
    }
};

方法2:

class Solution {
public:
    bool isPalindroms(string s,int l,int r) {
        while (++l < --r) {
            if (s[l] != s[r])
                return false;
        }
        return true;
    }
    bool validPalindrome(string s) {
        if (s.size() < 2)
            return true;
        int l = -1, r = s.size();
        while (++l < --r) {
            if (s[l] != s[r])
                return isPalindroms(s, l, r+1) || isPalindroms(s, l-1, r);
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值