[leetcode-680-Valid Palindrome II]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-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.

 思路:

从字符串两端向中间判断,如果相等则继续判断。

如果不相等,s[i] != s[j] ,那么判断 i+1到j 和i到j-1是否是回文,如果是的话即满足,都不是则不满足。

bool ispali(string& s,int start,int end)
{
    while (start <= end)
    {
        if (s[start] != s[end])return false;
        start++, end--;
    }
    return true;     
}
bool validPalindrome(string s)
{
    int n = s.length();
    if (n <= 2)return true;

    for (int i = 0; i < n;i++)
    {
        if (s[i] != s[n - i - 1])
        {
            return (ispali(s, i + 1, n - i - 1) || ispali(s, i, n - i - 2));
        }
         
    }
    return true;
}

参考:

https://leetcode.com/problems/valid-palindrome-ii/solution/#approach-2-greedy-accepted

以上是关于[leetcode-680-Valid Palindrome II]的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-680-Valid Palindrome II]

Leetcode 680: Valid Palindrome II

leetcode-680-Valid Palindrome II

Python 解LeetCode:680. Valid Palindrome II

[LeetCode] 680. Valid Palindrome II_Easy tag: Two Pointers

[leetcode]680. Valid Palindrome II有效回文II(可至多删一原字符)