您的位置:首页 > 其它

680. Valid Palindrome II

2017-10-16 22:11 351 查看
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.
题目不难,使用两次判断回文串的方法
java
class Solution {
public boolean validPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (left < right && s.charAt(left) != s.charAt(right)) {
return isValid(s, left + 1, right) || isValid(s, left, right - 1);
} else {
left++;
right--;
}
}
return true;
}
private boolean isValid(String s, int left, int right) {
while (left < right) {
if (left < right && s.charAt(left) != s.charAt(right)) {
return false;
} else {
left++;
right--;
}
}
return true;
}
}
python
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left, right = 0, len(s) - 1
while left < right:
if left < right and s[left] != s[right]:
return self.isValid(s, left + 1, right) or self.isValid(s, left, right - 1)
left, right = left + 1, right - 1
return True

def isValid(self, s, left, right):
while left < right:
if left < right and s[left] != s[right]:
return False
left += 1
right -= 1
return True


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