您的位置:首页 > 其它

[LeetCode] 680. Valid Palindrome II 验证回文字符串 II

2018-03-23 03:24 441 查看

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.

125. Valid Palindrome 的拓展,给定一个非空字符串,最多可删除1个字符,判断是否可以变成回文。

解法:还是从首尾两边开始比较,如果匹配就移动指针继续比较。当遇到不匹配的时候,删除左边的字符或者右边的字符,只要有一种能匹配就继续。

Python:

class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def validPalindrome(s, left, right):
while left < right:
if s[left] != s[right]:
return False
left, right = left+1, right-1
return True

left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right)
left, right = left+1, right-1
return True

C++:

class Solution {
public:
bool validPalindrome(string s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s[left] != s[right]) {
return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right);
}
++left, --right;
}
return true;
}

private:
bool validPalindrome(const string& s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) {
return false;
}
++left, --right;
}
return true;
}
};

 

类似题目:

[LeetCode] 125. Valid Palindrome 验证回文字符串

 

All LeetCode Questions List 题目汇总

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: