680. Valid Palindrome II

来源:互联网 发布:js获取时间并自动增加 编辑:程序博客网 时间:2024/06/08 17:33

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: TrueExplanation: 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.



最多只能删除一个字符,问给出的字符串操作后是否为回文字符串。用深度为1的深度优先搜索实现。


代码:

class Solution {public:    bool validPalindrome(string s) {    if(s.size() <= 2) return true;        return helper(s, 0, s.size()-1, 1);    }private:bool helper(const string &s, int l, int r, int cnt) {        while(l <= r-1) {        if(s[l] != s[r]) {        if(cnt <= 0) return false;        return helper(s, l+1, r, cnt-1) || helper(s, l, r-1, cnt-1);        }        l++; r--;        }        return true;}};