您的位置:首页 > 其它

680. Valid Palindrome II

2017-09-28 15:54 375 查看
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:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string dfs