题:https://leetcode.com/problems/valid-palindrome-ii/description/
题目
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.
题目大意
能否 最多删除一个字符使原字符串 变为 回文串。
思路
双指针i,j,左右对比字符串元素,若某元素不同,那么判断 i,j-1 或 i+1,j 是否为 回文串。
class Solution {
public boolean isPalindrome(String s,int i ,int j){
for(;i<j;i++,j--)
if(s.charAt(i)!=s.charAt(j))
return false;
return true;
}
public boolean validPalindrome(String s) {
for(int i=0,j = s.length()-1;i<j;i++,j--)
if(s.charAt(i)!=s.charAt(j))
return isPalindrome(s,i,j-1) || isPalindrome(s,i+1,j);
return true;
}
}