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[left] != s[right]的情况,我们可以尝试删除left或者right来进行判断是否是回文字符串

 

代码:

class Solution {
public:
    bool validPalindrome(string s) {
        int left = 0;
        int right = s.size() -1;
        bool moved = false;
        while(left < right){
            if(left == right)
                break;
            if(s[left] != s[right]){
                if(isPalindromeWithoutChar(s, left))
                    return true;
                if(isPalindromeWithoutChar(s, right))
                    return true;
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
private:
    bool isPalindromeWithoutChar(string &s, int idx){
        int left = 0;
        int right = s.size() - 1;
        while(left < right){
            if(left == idx)
                left++;
            else if(right == idx)
                right--;
            if(s[right] != s[left])
                return false;
            left++;
            right--;
        }
        return true;
    }
};

 

posted @ 2018-06-18 06:36  妖域大都督  阅读(147)  评论(0编辑  收藏  举报