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’.
Note:
1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

来自 https://leetcode.com/problems/valid-palindrome-ii/description/

2.题目分析:

给定一个非空字符串s,最多可以删除一个字符。 判断你是否可以将它作为回文。所谓的Palindrome就是对称的字符串,通过比较是s[left]和s[right],找出不一样的地方,这时候left和right是具有嫌疑的,究竟是要删除哪个,通过判断删除left或right后是否是回文,假如删除其中之一,满足条件返回true,否者返回false;

3.C++代码

//我的代码:(beats 73%)
bool isvalidPalindrome(string s)//回文判断
{
    int left = 0; int right = s.length()-1;
    while (left < right)
    {
        if (s[left] != s[right])
            return false;
        left++;
        right--;
    }
    return true;
}
bool validPalindrome(string s)
{
    int L = s.length();
    int left = 0; int right = L - 1;
    int cnt = 0;
    int index = -1;
    while (left < right)
    {
        if (s[left] != s[right])
        {
            string s1 = s.substr(left, right - left);
            string s2 = s.substr(left + 1, right - left);
            if (isvalidPalindrome(s1)|| isvalidPalindrome(s2))
                return true;
            else
                return false;
        }
        left++;
        right--;
    }
    return true;
}
//改进isvalidPalindrome函数,降低空间复杂度
bool isvalidPalindrome(string s, int left,int right)//回文判断
{

    while (left < right)
    {
        if (s[left] != s[right])
            return false;
        left++;
        right--;
    }
    return true;
}
bool validPalindrome(string s)
{
    int L = s.length();
    int left = 0; int right = L - 1;
    while (left < right)
    {
        if (s[left] != s[right])
        {
            //string s1 = s.substr(left, right - left);
            //string s2 = s.substr(left + 1, right - left);
            return (isvalidPalindrome(s, left, right - 1) || isvalidPalindrome(s, left + 1, right));
        }
        left++;
        right--;
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/qq_29689907/article/details/80334560