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

1.我的错误答案(有一种特殊情况没有考虑到)

    bool validPalindrome(string s) {
        int left = 0;
        int right = s.size() - 1;
        int count = 0;
        while(left <= right)
        {
            if (count > 1) return false;
            
            if (s[left] == s[right]){
                left++;
                right--;
            }
            else
            {
          // 可以看到这种解法,最终结果只能选择删掉不相同字符中的一个,然后继续进行。而我们需要的是删掉任意一个,只要有一种结果达到目标就可以
          // 而这种解法又无法进行回溯,所以这种解法是不可行的。
if (s[left + 1] == s[right]){ left++; count++; } else if(s[left] == s[right - 1]){ right--; count++; } else return false; } } return true; }

2.正确解法

    bool help(string::iterator left, string::iterator right)
    {
        while(left <= right)
        {
            if (*left != *right) return false;
            left++;
            right--;
        }
        return true;
    }
        bool validPalindrome(string s) {
            if (s.size() < 2) return true;
            string::iterator left = s.begin();
            string::iterator right = s.end() - 1;
            while(left <= right)
            {
                if (*left == *right)
                {
                    left++;
                    right--;
                }
                else{
                    return (help(left +1, right) || help(left, right - 1));
                }
            }
            return true;
        }

所以说做题要考虑周全啊,否则会浪费大量的时间呐。。。

原文地址:https://www.cnblogs.com/qiang-wei/p/12289100.html